简体   繁体   English

如何找到字符串 C# 的第 n 个单词?

[英]How to find the nth word of a string C#?

I am trying find the nth word of a string.我正在尝试查找字符串的第 n 个单词。 How do I do that using C#?如何使用 C# 做到这一点? I have tried splitting in spaces after that I don't know how to check each word.之后我尝试分割空格,我不知道如何检查每个单词。

You can check for spaces in the string and split.您可以检查字符串中的空格并拆分。 and string array from those segments.和来自这些段的字符串数组。 After that pass index to get the array item.之后通过索引获取数组项。 You can find the explanation here.你可以在这里找到解释。 Question number 12. http://xcelitsolutions.co.uk/JustCode/CSharp/AllQuestions.php?Chapter=Strings问题编号 12. http://xcelitsolutions.co.uk/JustCode/CSharp/AllQuestions.php?Chapter=Strings

Console.WriteLine("Enter the String");
string text = Console.ReadLine();//Enter the string
Console.WriteLine("Enter which word to show");//location of the word
int number = Convert.ToInt32(Console.ReadLine());
char[] mychar = {' '};
string[] wordslist = text.Split(mychar);
Console.WriteLine(wordslist[number-1]);

After you use the split() function an array is returned with number of elements = number of words that the string has been split into.使用 split() function 后,将返回一个数组,其中元素数 = 字符串已拆分成的单词数。 The split occurs in the same order.拆分以相同的顺序发生。 Simply call the index of the word you want.只需调用您想要的单词的索引。

string phrase = "The quick brown    fox     jumps over the lazy dog.";
string[] words = phrase.Split(' ');
Console.Writeline(words[5]); // prints 'over'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM