0

i want to create a simple program that i have a array of strings and for each string i want to check if it contains specified character, i want to remove it.first of all i replace the specified characters with space and when i tried to trim the spaces it doesn't work Here it is my code

char[] arr = new char[] {' '};
for (int i = 0; i < words.Length; i++)
{
    words[i] = words[i].Replace('0', ' ');
    words[i] = words[i].Trim(arr);
}

3 Answers 3

4

If you want to remove all spaces, instead of words[i] = words[i].Trim(arr);, you can use:

words[i] = words[i].Replace(" ", string.Empty);

Personally, I would do this for your first removal (0) as well:

words[i] = words[i].Replace("0", string.Empty); // Remove all "0" characters
words[i] = words[i].Replace(" ", string.Empty); // Remove all spaces

Or, even:

words[i] = words[i].Replace("0", string.Empty).Replace(" ", string.Empty); 
Sign up to request clarification or add additional context in comments.

Comments

3

Trim() only removes leading and trailing spaces. It won't remove spaces in the middle of a string. There's really no need to do all that work though. You can make a single call to Replace() by calling the appropriate overload:

for(int i = 0; i < words.Length; i++)
    words[i] = words[i].Replace("0", "");

1 Comment

+1 for explaining what trim does and why it's the wrong tool for the job.
1

and for people who like one-liners:

words = words.Select(i => i.Replace("0", "").Replace(" ", "")).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.