Darkbound
Darkbound

Reputation: 3434

Remove spaces from a string C# (something simple!)

Hi guys I can't find out why my code is not working, any help would be really appreciated!

I have a given string filled with numbers and space between each number I have to remove the spaces so that I get all the numbers glued to each other..

    string nums = "1 2 3 4 5";
    for (int i = 0; i < nums.Length; i++)
    {
        if (nums[i].ToString() == " ")
        {
            nums[i].ToString() = "";
        }
    }

I also tried using .Replace(" ", ""); but again no success, I can't figure out where I'm doing it wrong.. I need a simple, beginner friendly solution!

Upvotes: 0

Views: 165

Answers (3)

DotNetRussell
DotNetRussell

Reputation: 9857

This method will remove the spaces out of your string. What it does is iterates through each char and then compares it to the UTF-16 value for space. If it's a space it won't add it.

public String RemoveSpaces(String withSpaces){
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < withSpaces.Length; i++)
    {
        if (withSpaces[i] != 32)
        {
           sb.Append(withSpaces[i]);
        }
    }

    return sb.ToString();
}

Upvotes: 1

xxbbcc
xxbbcc

Reputation: 17327

You're assigning to the output of a function call (ToString()) which is wrong. Use String.Replace to replace characters in a string.

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Strings in .NET are immutable. Calling nums[i].ToString() gives you a new string, without modifying nums.

Replace is the way to go, but you have to assign result back to nums:

string nums = "1 2 3 4 5";

nums = nums.Replace(" ", "");

It's necessary, because Replace does not modify source string. It returns new one instead.

Upvotes: 5

Related Questions