Reputation: 33
I'm trying to remove spaces and certain symbols in front of the usable part of a string. I'm using a while loop and an if statement. The while loop runs before the if statement, but despite this it only gets stuck in the while loop when both the while and if condition is true.
string newNameTemp = " [i]";
while (newNameTemp.StartsWith(" ")) {
newNameTemp.Remove(0,1);
Console.WriteLine("1");
}
if (newNameTemp.StartsWith("[i]")) {
newNameTemp.Remove(0,3);
Console.WriteLine("2");
}
This just writes 1 repeatedly in the console
Upvotes: 0
Views: 167
Reputation: 1
string newNameTemp = " [i]";
newNameTemp = newNameTemp.Replace(" ", "");
if (newNameTemp.StartsWith("[i]"))
{
newNameTemp = newNameTemp.Remove(0, 3);
Console.WriteLine("2");
}
Just Replace all space in giving string with "" and remove special characters.
Upvotes: 0
Reputation: 36
You need to assign the variable back to itself when you remove the space
string newNameTemp = " [i]";
while (newNameTemp.StartsWith(" ")) {
newNameTemp = newNameTemp.Remove(0,1);
Console.WriteLine("1");
}
if (newNameTemp.StartsWith("[i]")) {
newNameTemp = newNameTemp.Remove(0,3);
Console.WriteLine("2");
}
for example: https://dotnetfiddle.net/K363wM
Upvotes: 1
Reputation: 1183
As mentioned in the docs. https://learn.microsoft.com/en-us/dotnet/api/system.string.remove?view=netframework-4.8
.Remove()
does not change the original string, but returns a new altered string, so changing the code to
string newNameTemp = " [i]";
while (newNameTemp.StartsWith(" ")) {
newNameTemp = newNameTemp.Remove(0,1);
Console.WriteLine("1");
}
if (newNameTemp.StartsWith("[i]")) {
newNameTemp = newNameTemp.Remove(0,3);
Console.WriteLine("2");
}
Should fix your issue.
Upvotes: 0