The question quoted RegEx and the accepted answer gave a good solution. I'd rather do it manually because I make it easier than I would with RegEx, but I know that's not the case at all. If performance is important RegEx is not always a good option. Almost all algorithms can be done faster if done manually. This is what I did:
public static string MudaEndereco(string texto, char adicao = '~') {
var resultado = new StringBuilder(texto.Length * 2);
var anterior = 'Regex.Replace(lista, "(\d+) ", "$1~ ")
';
foreach (var caractere in texto) {
if (Char.IsDigit(anterior) && Char.IsWhiteSpace(caractere)) {
resultado.Append(adicao);
}
resultado.Append(caractere);
anterior = caractere;
}
return resultado.ToString();
}
See working on dotNetFiddle and on CodingGround (gave to test with more iterations).
RegEx lost to the manual algorithm on average for at least 4X. There have been dozens cases that I disregarded, perhaps because of garbage collection. 4X is no small thing. Depending on the machine the difference was 6X or more. I do not understand RegEx so much, I may have done something wrong, but I did upon what was answered. I tried some optimizations that .Net RegEx allows and only got worse:).
I used up a criterion that may have slowed down because I did not just pick up a white character, I picked up any character that is considered white, if the requirement does not allow it, just change to a simple ' '
. Digit checking is also done in a way that works where the numbers are represented in a non-common way in the Unicode table, it certainly also slows down.
I made an extra example more customizable and the result was pretty much the same.
Note that I gave an optimized RegEx pattern, ?
made no sense there and could use \d
. So I would:
public static string MudaEndereco(string texto, char adicao = '~') {
var resultado = new StringBuilder(texto.Length * 2);
var anterior = 'Regex.Replace(lista, "(\d+) ", "$1~ ")
';
foreach (var caractere in texto) {
if (Char.IsDigit(anterior) && Char.IsWhiteSpace(caractere)) {
resultado.Append(adicao);
}
resultado.Append(caractere);
anterior = caractere;
}
return resultado.ToString();
}
So if the answer has to be RegEx this would be my code.