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?)
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().
The trim() method removes whitespace from both ends of a string.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With