我需要帮助使用C#中的Split
函数,用户需要输入三个或更多单词的短语。我已经知道用户的第一个单词是什么。例如,如果用户输入“Microsoft Visual Studio 2015”,我已经知道用户将输入“Microsoft”。如何使用 Split
剪切掉第一个单词并将其余的短语作为字符串返回?
char[] separators = { ' ' };
string secondword = myString.Split(separators, 2)[1];
这将给你正确的输出。使用带有int参数的split语句指定您要返回最多2个子字符串,数组索引[1]将第二个子字符串(第一个空格后的任何内容)指定为输出。
如果您需要第一个单词,可以采用类似的方法:
char[] separators = { ' ' };
string firstword= myString.Split(separators, 2)[0];
.Split
函数的第二个参数(数字2)上出现错误,提示“参数2:无法将'Int'转换为'Char'。”有什么帮助吗? - user5947033String.Substring()
:string input = "Microsoft Visual Studio 2015";
string result = input.Substring(input.IndexOf(' ') + 1);
Replace()
方法,例如:string str = "Microsoft Visual Studio 2015";
str = str.Replace("Microsoft","");
Substring()
方法,例如:str = str.Substring(("Microsoft".Length + 1), str.Length - ("Microsoft".Length + 1));
string value = "Microsoft Visual Studio 2015";
string expected = "Microsoft ";
if (value.StartsWith(expected))
{
value = value.Substring(expected.Length);
}
如果您愿意切割并重新构建字符串,您可以使用 String.Split
来切割字符串,然后使用 Enumerable.Skip
跳过第一个单词,最后使用 String.Join
构建新的字符串:
var str = "Microsoft Visual Stuio";
str = string.Join(" ", str.Split(' ').Skip(1));
有一个overload的String.Split()
方法,它接受一个整数作为参数,根据数组中的字符将字符串分割成最多数量的子字符串。它的参数应该是char[]
和int
,像这样:
string input = "Microsoft Visual Studio 2015";
string output = input.Split(new[] {' '}, 2)[1];
0
代替1
。这将仅返回第一个单词。 - Salah Akbari
myString.Split(" ",2)
? - Mathias R. Jessen