Phiter
Phiter

Reputation: 14992

Getting first name on name string with substring fails [C#]

So i have this piece of code:

MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");

lets suppose the name is "Phiter Fernandes", ok it will say:

Welcome, Phiter!

But if the name is just "Phiter" it will stop and not run the rest of the code. Obviously is because there are no spaces for the substring method to retrieve the first name.

But i don't want it to skip the rest of the code, i want it to work even if there is no space.

I tried using the try catch, just like this:

    try
 {
     MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
 }
catch
 { 
     MessageBox.Show("Welcome," + name + "!");
 }

It works, but there is an annoying sound when the code runs the catch. Is there any other way around this? A different way of getting the first name, perhaps?

Upvotes: 0

Views: 124

Answers (2)

mchl0208
mchl0208

Reputation: 69

You can try more than one options.

  1. Replace usign Regex.

    string input = "Your string      " + "whitespace.";
    string pattern = "\\s+";
    string replacement = " "; 
    Regex rgx = new Regex(pattern); 
    string result = rgx.Replace(input, replacement);
    
  2. check if space exists.

    if(name.Contains(" "))
        MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
    
  3. trim spaces

    string fullName = name;
    var names = fullName.Split(' ');
    string firstName = names[0];
    MessageBox.Show("Welcome," + firstName + "!");
    

Let me know which one did you use!

Upvotes: 0

Cyral
Cyral

Reputation: 14153

Try splitting the string wherever there is a space, and selecting the first element, which will always be the first name.

MessageBox.Show("Welcome," + name.Split(' ')[0] + "!");

Upvotes: 4

Related Questions