简体   繁体   中英

How would you go about removing whitespace from a string without the use of methods such as .trim or .replace?

I'm also not allowed to use lists.

My initial thought process for this was to take the initial string then to turn that into a char array. Then after copy everything that is not a space to a second char array. Then convert that char array back to a string.

So quickly it would look something like this;

char[] firstArray;
char[] secondArray;
string someString;

for (int i = 0; i < someString.Length; i++)
{
    firstArray = someString.ToCharArray();
    secondArray = new char[someString.Length];

    for (int j = 0; j < firstArray.Length; j++)
    {
        if (firstArray[j] != ' ') 
        {
            secondArray[j] = firstArray[j];
        }
    }

    someString = secondArray.ToString();
}

But when I initialise the second char array it would contain an extra char with no value if there was a space in it initially, since it was initialised to the same size as the first char array. Would I have to do a similar loop before just to count the amount of non-spaces then initialise secondArray based off that or is there a much simpler way than all of this that I am missing? (Without the use of .trim, .replace(or anything like them) or lists)

Any help would be appreciated.

A String already implements IEnumerable<char> , so no need to turn it into an array to begin with. You can enumerate it directly and remove whitespace chars. Eg:

string x = "  Hello, world";
string trimmed = new String(x.Where(c => !Char.IsWhiteSpace(c)).ToArray());

Your code re-creates the firstArray array every time. And I'm not sure what the inner loop is for. Your code fixed:

char[] firstArray;
char[] secondArray;
string someString = "Blah blah blah";

firstArray = someString.ToCharArray();
secondArray = new char[someString.Length];

int newLength = 0;

for (int i = 0; i < firstArray.Length; i++) {
    if (firstArray[i] != ' ') {
        secondArray[newLength++] = firstArray[i];
    }
}

someString = new string(secondArray, 0, newLength);

Another way using StringBuilder:

string someString = "Blah blah blah";
System.Text.StringBuilder sb = new System.Text.StringBuilder();

foreach(char c in someString) {
    if (!Char.IsWhiteSpace(c)) {
        sb.Append(c);
    }
}
someString = sb.ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM