0

from textbox inside winform I'm taking user input as csv and I'm putting them into string array where I iterate trough that array to create some object with first and last names.

if(txtAuthors.Text != string.Empty)
{
   if(txtAuthors.Text.Contains(","))
   {
      if (authorsInput.Count() > 0)
      {
         foreach (string name in authorsInput)
         {
            name.TrimStart(); 
            string[] firstAndLastName = name.Split(' ');
            string fname = firstAndLastName[0];
            string lname = firstAndLastName[1];
         }
      }    
   }
}

Problem is that only first author before first comma is added as it should (fname and lname) and other only lastname. So I've tried as you can see to trim name to remove whitespace from array members but problem is still the same.

What I'm doing wrong here?

update:this now works

string[] firstAndLastName = name.TrimStart().Split(' ');

but I still don't know why this don't work

name.TrimStart();
string[] firstAndLastName = name.Split(' ');
user2783193
  • 992
  • 1
  • 12
  • 37

2 Answers2

2

You can use Trim() cuts all whitespaces before and after
'fname = fname.Trim();'

1110
  • 7,829
  • 55
  • 176
  • 334
2

Calling name.TrimStart() doesn't result in a variable name without initial blanks because strings are immutable objects.
You cannot modify a string in place. You always need to assign the result of the operation to a new string.

Your second option works because it is like:

string newname = name.TrimStart();
string[] firstAndLastName = newname.Split(' ');

Also, notice that I use a new variable for the result of the TrimStart. This is required if you do that inside the foreach loop because it is not allowed to change the foreach iteration variable

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286