Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform Trim() while using Split()

Tags:

string

c#

trim

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?)

like image 447
citronas Avatar asked Dec 29 '09 22:12

citronas


People also ask

How do you use split and trim together?

Split and Trim String input = " car , jeep, scooter "; To remove extra spaces before and/or after the delimiter, we can perform split and trim using regex: String[] splitted = input. trim().

What will trim () do?

The trim() method removes whitespace from both ends of a string.

What is trim () function in Java?

The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.


1 Answers

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); 
like image 170
Marc Gravell Avatar answered Sep 25 '22 00:09

Marc Gravell