You have a code design problem here:
foreach (string word in words)
if (word.ToUpper() == word)
{
string lastname = string.Join(" ", word);
Console.WriteLine(word);
}
What you want to do is to write the lastname once, right? So let's split the algorithm:
- Get all words from the string: done
string[] words = fullName.Split(' ');
- Read first word, if it's uppercase, save it
- Repeat 2 for the next word until it isn't uppercase
- Join all the saved words
- Print the result
We don't need to "save" the words thanks to a handy class named StringBuilder, so it would go like this:
string fullName = "BELAMONTE VALVERDE Allechandro Jesus";
string[] words = fullName.Split(' ');
StringBuilder sb = new StringBuilder();
foreach (string word in words)
if (word.ToUpper() == word)
{
sb.Append(word + " ");
}
else
break; // That's assuming you will never have a last name's part after a first name's part :p
if (sb.Length > 0)
sb.Length--; // removes the last " " added in the loop, but maybe you want it ;)
Console.WriteLine(sb.ToString());