I would like to know if there is a simple way to find consecutive (equal) numbers in a string, so that you can replace that string with a single value.
For example:
string input = "Abc111de2234";
string output = "Abc1de234";
I would like to know if there is a simple way to find consecutive (equal) numbers in a string, so that you can replace that string with a single value.
For example:
string input = "Abc111de2234";
string output = "Abc1de234";
You can do this with a character scan and a single loop, like this (Example in dotnetfiddle) :
string input = "Abc111de2234";
string output = string.Empty; // Desejado: "Abc1de234";
char[] numbers = new []{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
if(!string.IsNullOrWhiteSpace(input))
for(int i = 0; i < input.Length; i++)
if (i > 0)
{
if (numbers.Contains(input[i]))
{
if(input[i] != input[i-1])
output += input[i];
}
else
output += input[i];
}
else
output += input[i];
Console.WriteLine(output);
Other ways to do this include using regular expressions, for example, but I believe this would be less performative.
I would do so:
using static System.Console;
public class Program {
public static void Main() {
var texto = "Abcc111de12234";
var lista = new char[texto.Length];
for (int i = 0, j = 0; i < texto.Length; i++) if (!char.IsDigit(texto[i]) || (i == 0 || texto[i] != texto[i - 1])) lista[j++] = texto[i];
WriteLine(new string(lista));
}
}
See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .
The other answer's solution generates several string allocations and copies , making to slow application and consuming lots of memory , as well as causing pauses. There are other inefficiencies.