user3743340
user3743340

Reputation: 57

Trim all strings within a string array

I'm having trouble trimming all the whitespaces(tab, etc.) for a given string. I've tried a number of recommended solutions, but have yet have any sort of luck.

for example

["7 ", "  +", "1",  "/"  "0""]

needs to return

["7","+","1","/","0"]

Another aspect to consider is that

string[] substrings = Regex.Split(exp, "(\\()|(\\))|(-)|(\\+)|(\\*)|(/)");

must also be used, and I'm working on a passed in string.

Upvotes: 2

Views: 3164

Answers (2)

AlexD
AlexD

Reputation: 32576

You coud use Linq:

var a = new string[]{"7 ", "  +", "1",  "/", null, "0"};
var b = a.Select(x => x == null? null: x.Trim()).ToArray();

or do it in-place applying Trim to every element.


Another aspect to consider is that ...

This was not in the first edition of the question, and Regex is not considered in the answer.

Upvotes: 4

Mike
Mike

Reputation: 101

You can use Linq too.

string text = "My text with white spaces...";
text = new string(text.ToList().Where(c => c != ' ').ToArray());

Upvotes: 0

Related Questions