Perform Trim() while using Split()

70,265

Solution 1

Another possible option (that avoids LINQ, for better or worse):

string line = " abc, foo  ,     bar";
string[] parts= Array.ConvertAll(line.Split(','), p => p.Trim());

However, if you just need to know if it is there - perhaps short-circuit?

bool contains = line.Split(',').Any(p => p.Trim() == match);

Solution 2

var parts = line
    .Split(';')
    .Select(p => p.Trim())
    .Where(p => !string.IsNullOrWhiteSpace(p))
    .ToArray();

Solution 3

I know this is 10 years too late but you could have just split by ' ' as well:

string[] split= keyword.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);

Because you're also splitting by the space char AND instructing the split to remove the empty entries, you'll have what you need.

Solution 4

If spaces just surrounds the words in the comma separated string this will work:

var keyword = " abc, foo  ,     bar";
var array = keyword.Replace(" ", "").Split(',');
if (array.Contains("foo"))
{
    Debug.Print("Match");
}

Solution 5

I would suggest using regular expressions on the original string, looking for the pattern "any number of spaces followed by one of your delimiters followed by one or more spaces" and remove those spaces. Then split.

Share:
70,265
citronas
Author by

citronas

I studied computer science and math and completed my academic career with a PhD in computer science about machine learning and argument mining on text data. I've returned to the corporate sector and am currently working as a Senior Software Developer for a digital media agency where I focus on designing and implementing solutions with ASP.NET Core MVC and C#.

Updated on July 08, 2022

Comments

  • citronas
    citronas almost 2 years

    today I was wondering if there is a better solution perform the following code sample.

    string keyword = " abc, foo  ,     bar";
    string match = "foo";
    string[] split= keyword.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
    foreach(string s in split)
    {
      if(s.Trim() == match){// asjdklasd; break;}
    }
    

    Is there a way to perform trim() without manually iterating through each item? I'm looking for something like 'split by the following chars and automatically trim each result'.

    Ah, immediatly before posting I found

    List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();
    

    in How can I split and trim a string into parts all on one line?

    Still I'm curious: Might there be a better solution to this? (Or would the compiler probably convert them to the same code output as the Linq-Operation?)

  • citronas
    citronas over 14 years
    Oh, yeah you are absolutly right. Seems that I have to get used to the Any() Method ;) thanks
  • citronas
    citronas over 14 years
    Regex, haven't thought of that either, but you are right, would be a another possible solution. thanks
  • Eilon
    Eilon over 14 years
    I would be very much against using regular expressions for such a trivial problem. See codinghorror.com/blog/archives/001016.html regarding "now you have two problems."
  • Jonathan Olson
    Jonathan Olson over 14 years
    Well I'm hopeless at writing regular expressions, and would screw it up, so I wouldn't use it either TBH, but this seems a fairly simply pattern to search and replace and I would have thought would be faster than any method that does a .Trim() on each element after splitting.
  • Franck
    Franck over 10 years
    This solution does not work if a single value contain 1 or more spaces.
  • Rick
    Rick over 9 years
    The answer in stackoverflow.com/questions/1728303/… is more elegant maybe?
  • Ulysses Alves
    Ulysses Alves over 4 years
    @Morty Yeah, maybe. But you'll find that business rules are far more important than implementation details. Besides, both solutions work, so it's just good we have options.
  • Behzad Ebrahimi
    Behzad Ebrahimi over 4 years
    The Array.ConvertAll() is not available in .NET Compact Framework.
  • MarkMYoung
    MarkMYoung over 3 years
    You might've been 10 years too late for the OP, but this is exactly what I needed.
  • Jon Hallin
    Jon Hallin about 3 years
    This assumes there are no spaces in the individual entries though, otherwise those will be split up into separate words.
  • Zef
    Zef almost 3 years
    This also removes blank (IsNullOrWhiteSpace) entries, so that " abc, foo , , bar" (extra comma) gives 3 trimmed results rather than 4. This is what I needed, but didn't see this until I'd rolled my own :)