如何获取字符串的第一个单词。
string test = "hello, world"
我使用了test.Split(' ').FirstOrDefault()
,但它返回了"hello,
"。
我可以尝试添加逗号作为分隔符,但即使有逗号或空格,我仍只需要单词 'hello'。我的意思是,如果字符串test = "hello world",那么它也应该返回 "hello"。
Regex.Replace(str.Trim(), "[^a-zA-Z0-9]", " ").Split(' ').FirstOrDefault();
string pattern = @"^\w+";
string test = "hello, world";
var firstWord = Regex.Match(test, pattern);
Console.WriteLine(firstWord);
// output
// hello
不要忘记包含命名空间 'System.Text.RegularExpressions'
我认为你可以使用类似Char的东西,这样更容易理解。
例如:
string test = "Hello, world!";
string split = test.Split(' ')[0]; //Split by space
if (!Char.IsLetter(split.Last())) //Check if last character is letter
split = split.Remove(split.Length - 1); //If not, remove last character
Console.WriteLine(split); //Print out the word
string test = "Hello!?! world!";
怎么样? - Enigmativity
test.Substring(0,test.IndexOf(" ")).Trim(",");
或者只需使用循环来修剪非字母数字字符:Char.IsLetter
的test.Substring(0,test.IndexOf(" "))
。 - Jeremy Thompson