-1

I want to make textbox where user can input decimals, e.g. "1, 2, 3, 4". Then I split this into integer array using

array = Array.ConvertAll(str.Split(','), int.Parse);

When user input e.g. "1,,,,2,,3,4" there is en exception. How can I remove commas when string is immutable?

1

1 Answer 1

5

You can't remove the commas from the existing string - although you could create a different string before splitting. That's typically what you do with string processing - create a whole sequence of strings, performing replacements, trimming etc along the way.

A simpler solution is probably to use StringSplitOptions.RemoveEmptyEntries though:

string[] parts = str.Split(',', StringSplitOptions.RemoveEmptyEntries);
array = Array.ConvertAll(parts, int.Parse);

(Note that the String.Split(char, StringSplitOptions) overload is not available in the desktop framework; you'd need to call String.Split(char[], StringSplitOptions) - just change ',' to new[] { ',' } in the calling code.)

You could potentially include StringSplitOptions.TrimEntries too, so that "1, 2 , 3 ,4" would be handled equivalently to "1,2,3,4".

This is assuming you just want to handle users adding more commas than expected. It won't help if the user enters "1,2,xyz" for example.

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

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.