如何找到字符串中第五个空格的位置

本文关键字:空格 位置 第五个 何找 字符串 | 更新日期: 2023-09-27 18:36:48

我是.net Web表单的新手,所以任何人都可以帮助我。

如何找到字符串中第五个空格的位置 asp.net?

我有

string s="aa bb cc dd ee ff gg hh ii kk"
所以

我想让子字符串直到第五个空格,所以新字符串应该是:

"aa bb cc dd ee"

如何找到字符串中第五个空格的位置

获取子字符串"aa bb cc dd ee"

String.Join(" ", "aa bb cc dd ee ff gg hh ii kk".Split(' ').Take(5))

并找到第五个空间的位置,正如您最初要求的那样:

"aa bb cc dd ee ff gg hh ii kk".Split(' ').Take(5).Sum(a => a.Length + 1) - 1

解释:

  • .Split(' ') - 将字符串拆分为空格,因此我们现在有一个包含以下内容的string[]aa, bb, cc, dd, ee, ff, gg, hh, ii, kk
  • .Take(5) - 将该数组的前五个元素取IEnumerable<string>aa, bb, cc, dd, ee
  • .Sum(a => a.Length + 1) - 将各个元素的所有长度相加(在本例中为所有2,并为由于拆分而丢失的空间添加一个
  • - 1删除空间的额外计数

另一种方法是获取上面的子字符串.Length

你可以拆分字符串,只取前 5 个子字符串,然后将其重新连接在一起,如下所示:

string s = "aa bb cc dd ee ff gg hh ii kk";
string output = String.Join(" ", s.Split(new[] { ' ' }, 6).Take(5)); 
Console.WriteLine(output); // "aa bb cc dd ee"

或者对于更直接的方法,只需使用IndexOf,直到找到所需的空格数:

string s = "aa bb cc dd ee ff gg hh ii kk";
var index = -1;
for (int i = 0; i < 5; i++)
{
    index = s.IndexOf(" ", index + 1);
}
string output = s.Remove(index);
Console.WriteLine(output); // "aa bb cc dd ee"

或者...

var nrOfBlanks = 0;
var firstFive = new String(s.TakeWhile(c => 
                                        (nrOfBlanks += (c == ' ' ? 1 : 0)) < 5)
                             .ToArray());

。仅仅因为使用稍微过于复杂的 Linq 表达式的字符串操作感觉如此有趣和性感。

您可以使用

String.Split方法,例如;

string s = "aa bb cc dd ee ff gg hh ii kk";
var array = s.Split( new string[] {" "}, StringSplitOptions.RemoveEmptyEntries);
string newstring = "";
for (int i = 0; i < 5; i++)
     newstring += array[i] + " ";
Console.WriteLine(newstring.Trim());

输出将是;

aa bb cc dd ee

这里有一个Demonstration.

您可以使用 string.split(' ') 返回字符串数组。

string s = "aa bb cc dd ee ff gg hh ii kk";
//
// Split string on spaces.
// ... This will separate all the words.
//
string[] words = s.Split(' ');
foreach (string word in words)
{
    Console.WriteLine(word);
}

因此,一旦你得到数组,你就可以连接任意数量的单词。因此,在您的情况下,循环到单词数组中的第 4 个索引,并在两者之间连接插入空白。

使用 Substring

string Requiredpart= s.Substring(0, s.IndexOf(' ', theString.IndexOf(' ') + 4));

您可以使用空白字符进行拆分

string[] words = s.Split(' ');

然后根据需要撰写单词。

我希望你觉得这有用。尼古拉

linq 版本:

var fifthBlankIndex = s.Select((c, index) => new{ c, index })
 .Where(x => Char.IsWhiteSpace(x.c))
 .ElementAtOrDefault(4);
int result = -1;
if(fifthBlankIndex  != null)
    result = fifthBlankIndex.index;  // 14

演示

编辑 如果您只想使用前五个单词,这是一个完全不同的要求:

string fiveWords = string.Join(" ", s.Split().Take(5));