2

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.

3
  • 1
    How about a simple loop? It's not the kind of task one needs a "recommended solution" for. Commented Sep 11, 2014 at 3:23
  • 1
    Can't you loop it with a simple for and Trim each? Commented Sep 11, 2014 at 3:23
  • Why must the regex shown be "considered"? Commented Sep 11, 2014 at 3:42

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

LINQ is beautiful and all, but "within a string array" probably means he wants to mutate the array.
.Where(x => !string.IsNullOrEmpty(x)).Select(x => ...
@slugster Thanks! "".Trim is not a problem, but nulls could be. I updated the answer.
Do you expect null in a?
0

You can use Linq too.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.