S
S
samsungovetch2018-07-10 05:03:19
C++ / C#
samsungovetch, 2018-07-10 05:03:19

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

3 answer(s)
A
Alexey Nemiro, 2018-07-10
@samsungovetch

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");

If you use a loop, then you need to create a new string, but instead of string , it is better to use StringBuilder , because when adding data to string , the string will be constantly re-created, which may ultimately have a negative impact on performance:
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());

If you think carefully and if it is acceptable, then the problem can be solved with only one StringBuilder (one instance), which will initially have a string to process, using the Remove method to remove unnecessary data. With this implementation, a for loop will be used .

R
Roman Mirilaczvili, 2018-07-10
@2ord

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.

O
Oleg, 2018-07-10
@slayez

Start the loop from the last element, not from the first

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question