如何使用IndexOf方法移除字符串中的所有空格?
实现方案
你当前的代码作用是统计空格数量后加1得到单词数,若要基于IndexOf方法实现移除所有空格的功能,只需要在每次找到空格位置后,删除对应位置的空格再继续查找即可,参考实现如下:
string text = "Hello. What time is it?"; int position = text.IndexOf(' '); while (position != -1) { // 删除当前位置的空格 text = text.Remove(position, 1); // 从当前位置继续查找下一个空格 position = text.IndexOf(' ', position); } Console.WriteLine(text); // 输出结果:Hello.Whattimeisit?
逻辑说明
- 第一次调用
IndexOf(' ')找到第一个空格的位置,找不到直接返回-1结束流程 - 每次删除空格后,不需要从头开始查找,直接从当前位置继续找下一个空格即可,性能更高
- 如果你需要同时保留原字符串做单词统计,可以先复制原字符串再执行移除空格的操作,避免修改原字符串影响统计逻辑,示例如下:
string originalText = "Hello. What time is it?"; // 原有单词统计逻辑(优化为while循环,减少无效遍历) int spaceCount = 0; int pos = originalText.IndexOf(' '); while (pos != -1) { spaceCount++; pos = originalText.IndexOf(' ', pos + 1); } Console.WriteLine($"单词数量:{spaceCount + 1}"); // 移除空格逻辑 string textWithoutSpaces = originalText; int spacePos = textWithoutSpaces.IndexOf(' '); while (spacePos != -1) { textWithoutSpaces = textWithoutSpaces.Remove(spacePos, 1); spacePos = textWithoutSpaces.IndexOf(' ', spacePos); } Console.WriteLine($"无空格字符串:{textWithoutSpaces}");
内容的提问来源于stack exchange,提问作者Mathhh
相关产品推荐
相关产品推荐

