如何使用IndexOf删除空格



我创建了以下内容来计算字数。现在我需要使用IndexOf删除所有空格。我被卡住了。有人能帮忙吗?它必须是一些简单的东西,但我想不通。

string text = "Hello. What time is it?";
int position = 0;
int noSpaces = 0;
for (int i = 0; i < text.Length; i++)
{
position = text.IndexOf(' ', position + 1);
if (position != -1)
{ noSpaces++; }
if (position == -1) break;
}
Console.WriteLine(noSpaces + 1);

如果您只想删除文本中的空格,使其看起来像:Hello.Whattimeisit?,那么您所需要做的就是使用String.Replace:

string text = "Hello. What time is it?";
string textWithNoSpaces = text.Replace(" ", "");
Console.WriteLine(textWithNoSpaces); // will print "Hello.Whattimeisit?"

如果你想将文本拆分成单独的单词,那么你会想使用字符串。拆分:

string text = "Hello. What time is it?";
string[] words = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // "RemoveEmptyEntries" will remove any entries which are empty: ""
// words[0] > Hello.
// words[1] > What
// etc.

然后,如果您需要Hello.Whattimeisit?:形式的文本,您可以使用String.Concat计算文本中的单词数,然后将它们组合起来

int numberOfWords = words.Length;
string textWithNoSpaces = string.Concat(words);

更新:这就是使用String.IndexOf&String.Substring:

这是一个非常草率的例子,但它完成了任务

string text = "Hello. What time is it?";
string newText = string.Empty;
int prevIndex = 0;
int index1 = 0;
int index2 = 0;
int numberOfWords = 0;
while (true)
{
index1 = text.IndexOf(' ', prevIndex);
if (index1 == -1)
{
if (prevIndex < text.Length)
{
newText += text.Substring(prevIndex, (text.Length - prevIndex));
numberOfWords += 1;
}
break;
}
index2 = text.IndexOf(' ', (index1 + 1));
if ((index2 == -1) || (index2 > (index1 + 1)))
{
newText += text.Substring(prevIndex, (index1 - prevIndex));
numberOfWords += 1;
}
prevIndex = (index1 + 1);
}
Console.WriteLine(numberOfWords); // will print 5
Console.WriteLine(newText); // will print "Hello.Whattimeisit?"
Console.ReadLine();

如果你的要求是计算字数,你不能试试吗?

string text = "Hello. What time is it?";
var arr = text.Split(' ');
var count = arr.Length;

.Net Fiddle

字符串是不可变的,因此您无法仅使用需要多次更改的IndexOf来实现它。如果您需要使用特定的方法来实现它,我认为StringBuilder是唯一的方法。然而,如果这不是一项任务,并且您计划在实际应用程序中使用它,我强烈建议您不要这样做,因为这确实是一项繁重的过程。

最新更新