I have a string as follows,
var str = ' test'
when i call the expression
str.split(' ') I end up with 2 items in an array.
How can i split it and end up with only test, ie something that has a non-empty space in c# ?
I have a string as follows,
var str = ' test'
when i call the expression
str.split(' ') I end up with 2 items in an array.
How can i split it and end up with only test, ie something that has a non-empty space in c# ?
You can use the StringSplitOptions
overload:
var str = " test words cat dog ";
String[] words = str.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
int wordCount = words.Length;
foreach(String word in words)
{
Console.WriteLine(word);
}
Console.WriteLine("Count: " + wordCount);
There's probably a more efficient way to do this, but this still solves the problem:
List<string> strings = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
int stringCount = strings.Count();
Try str.Trim().Split(' ')
this will strip away leading and trailing whitespace. If you're trying to turn " a string with words "
into ["a", "string", "with", "words"]
this will achieve that.
You'll still have to account for extra spaces between the words though
Edit: this is a much better answer (essentiall use Regex or str.Split(' ', StringSplitOptions.RemoveEmptyEntries)
: https://stackoverflow.com/a/18410393/5278363