Answer the question
In order to leave comments, you need to log in
C# - How to remove a character from a string when processing a string character by character in a loop?
Let's say the string "ab+0.1973-1.1" is given.
It is processed character by character via foreach. It is necessary to remove from each group of consecutive digits, in which there are more than two digits and which is preceded by a period, all digits, starting from the third.
With what is it done? I found a way to delete characters up to a certain sign, but there is no certain sign here, because a string like "ab+0.1973+1.1" can be given and won't work anymore.
Answer the question
In order to leave comments, you need to log in
It's easiest to use regular expressions, if possible:
string value = "ab+0.1973-1.1";
string result = Regex.Replace(value, @"(\.\d{2})\d+", "$1");
string inputString = "ab+0.1973-1.1";
var result = new StringBuilder();
bool hasDot = false;
int digits = 0;
foreach(char ch in inputString)
{
if (char.IsDigit(ch) && hasDot)
{
digits++;
}
else
{
digits = 0;
hasDot = (ch == '.');
}
if (digits <= 2)
{
result.Append(ch);
}
}
Console.WriteLine(result.ToString());
Do not touch the original string, but form a new one character by character. Characters to be removed can be marked with boolean flags (variables). That is, while flagged, skip without copying characters to the target string.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question