There is a text from which it is necessary to take words beginning with a capital letter.

решИла нЕ Упрощать и зашифРОВАтЬ Все послаНИЕ дАже не Старайся нИЧЕГО у тЕбя нЕ получится с расшифРОВкой Сдавайся НЕ твоего ума Ты не споСОбЕн Но может быть если особенно упорно подойдешь к делу будет Трудно конечнО Код ведЬ не из простых очень ХОРОШИЙ код то у тебя все получится и я буДу Писать тЕбЕ еще чао 

my code

 data.Split(' ').Select(x => x).Where(x=>char.IsUpper(x[0])).Reverse().ToList(); 

Why then he does not take all the words that begin with a capital letter My result

 Писать ХОРОШИЙ Трудно Но Ты НЕ Старайся Все Упрощать 

And it should turn out

 Писать ХОРОШИЙ Код Трудно Но Ты НЕ Сдавайся Старайся Все Упрощать 

What's wrong with my code *

    3 answers 3

    I think the problem is that you divide by space, and you need to include the end of the line in the separating characters (and Tab, probably).

    Another potential problem: You take the first character of a word without checking the word length.

    Well, the Select(x => x) construction does not change the sequence and is thus not needed.

      You can solve the problem of finding delimiters, tabs, line breaks and other commas using regular expressions:

       string pattern = @"\b\p{Lu}.*?\b"; var words = Regex.Matches(data, pattern) .Cast<Match>().Select(m => m.Value).Reverse(); Console.WriteLine(String.Join(" ", words)); 
      • \b - word boundary
      • \p{Lu} - capital letter
      • .*? - any characters, but as little as possible (i.e., the next \b will coincide with the nearest word boundary)
          data.Split(' ', '\n') .Where(x => !string.IsNullOrEmpty(x)) .Where(x => char.IsUpper(x[0])) .Reverse(); 

        Added a line break to delimiters and check that the string is not empty, as VladD advised, now works correctly.

        • 2
          StringSplitOptions.RemoveEmptyEntries - Qwertiy