Splitting with multiple spaces

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a text file that appears to be delimited by multiple spaces. The
split function will only work with one space if I am correct. Is there some
way to split this file into an array without getting the extra spaces?
 
Hi Christine!

if understood you're needs correctly, i suggest you to use
System.Text.Regex's Split() function instead of the String's one. It
supports a String parameter.
 
I have a text file that appears to be delimited by multiple spaces. The
split function will only work with one space if I am correct. Is there some
way to split this file into an array without getting the extra spaces?

Use the Regex (System.Text.RegularExpressions.Regex) split instead as it
allows pattern matching rather than single character or specific string
matching.

Regex r = new Regex(" +");
string [] splitString = r.Split(stringWithMultipleSpaces);
 
Okay that helps with the spaces, but now I have a problem of a carriage
return at the end of each line that Regex doesn't take care of. Is there
some way to take care of this as well as the multiple spaces? Thanks so much
for the help!

Tom Porterfield said:
I have a text file that appears to be delimited by multiple spaces. The
split function will only work with one space if I am correct. Is there some
way to split this file into an array without getting the extra spaces?

Use the Regex (System.Text.RegularExpressions.Regex) split instead as it
allows pattern matching rather than single character or specific string
matching.

Regex r = new Regex(" +");
string [] splitString = r.Split(stringWithMultipleSpaces);
 
Okay that helps with the spaces, but now I have a problem of a carriage
return at the end of each line that Regex doesn't take care of. Is there
some way to take care of this as well as the multiple spaces? Thanks so much
for the help!

You have several options. You could use the System.String.Replace method
to replace the carriage return with an empty string, or you could use
System.String.TrimEnd - Ex:

string newString =
stringWithCarriageReturn.TrimEnd(new char[]{'\r','\n',' '});

Note that the above will also trim any trailing spaces.
 
Thank you so much, that was very helpful!

Tom Porterfield said:
Okay that helps with the spaces, but now I have a problem of a carriage
return at the end of each line that Regex doesn't take care of. Is there
some way to take care of this as well as the multiple spaces? Thanks so much
for the help!

You have several options. You could use the System.String.Replace method
to replace the carriage return with an empty string, or you could use
System.String.TrimEnd - Ex:

string newString =
stringWithCarriageReturn.TrimEnd(new char[]{'\r','\n',' '});

Note that the above will also trim any trailing spaces.
 
Back
Top