How can I replace a part of a string by itself plus the "~" character?

Asked

Viewed 1,511 times

13

How can I replace a part of a string by itself plus the character "~"?

I’m doing it this way: only when the string has two equal numbers as the 51 that comes just after AP and the contained in the 17513322 o Replace makes the exchange in both places and I just want you to do the Replace in full number.

My string should look as follows:

RUASANTA HELENA, 769~ AP 51~ BL H JD ALVORADA~ 17513322~

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string lista = "RUASANTA HELENA, 769  AP 51 BL H JD ALVORADA~ 17513322 ";

        var match = Regex.Match(lista, "[0-9]+");
        while (match.Success)
        {
            lista = lista.Replace(match.Value, match.Value + "~");
            match = match.NextMatch();
        }
        System.Console.Write(lista);    
    }       
}
  • 1

    This should also work: http://ideone.com/59v7or

  • @stderr, thanks also work.

3 answers

19


If the full number is always followed by a space, you can use the Pattern "([0-9]+?)" and replace by the match that occurred within the parentheses plus the ~ and a space (that gave match also):

string lista = "RUASANTA HELENA, 769  AP 51 BL H JD ALVORADA~ 17513322 ";
lista = Regex.Replace(lista, "([0-9]) ", "$1~ ");

Example in Dotnetfiddle.

7

The question cites Regex and the accepted answer gave a good solution. I prefer to do it manually because I make it easier than I would with Regex, but I know that’s not the case with everyone. If performance is important Regex is not always a good option. Almost all algorithms can be done faster if produced manually. That’s what I did:

public static string MudaEndereco(string texto, char adicao = '~') {
    var resultado = new StringBuilder(texto.Length * 2);
    var anterior = '\0';
    foreach (var caractere in texto) {
        if (Char.IsDigit(anterior) && Char.IsWhiteSpace(caractere)) {
            resultado.Append(adicao);
        }
        resultado.Append(caractere);
        anterior = caractere;
    }
    return resultado.ToString();
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Regex lost to the manual algorithm on average by at least 4X. There were dozens of cases I disregarded, perhaps because of garbage collection. 4X is no small thing. Depending on the machine the difference was in 6X or more. I do not understand so much of Regex, I may have done something wrong, but I did on top of what was answered. I tried some optimizations that the Regex’s. Net allows and only worsened :).

I even used a criterion that may have slowed down because I didn’t just take a white character, I took any character that is considered a white one, if the requirement doesn’t allow it is just switch to a simple one ' '. The check of digits is also done so that it works where the numbers are represented in an unusual way in the Unicode table, this certainly also slows down.

I made an extra example more customizable and the result was pretty much the same.

Note that I have optimized the Regex standard, the ? made no sense there and could use \d. Then I would:

Regex.Replace(lista, "(\\d+) ", "$1~ ")

So if the answer had to be Regex this would be my code.

5

String.Replace (String, String)

Returns a new sequence in which all occurrences of a String specified are replaced by another specified String.

Syntax

public string Replace(
    string oldValue,
    string newValue
)

Example

public class Example
{
   public static void Main()
   {
      String s = "aaa";
      Console.WriteLine("The initial string: '{0}'", s);
      s = s.Replace("a", a+"~");
      Console.WriteLine("The final string: '{0}'", s);
   }
}

String.Concat method (String, String)

Concatenates two specified String instances.

Syntax

public static string Concat(
    string str0,
    string str1
)

Example

string str0 = "teste";
string str1 = "~";

str0 = string.Concat(str0, str1)

Good luck!

  • With String.Replace() I would need to know the index at the beginning and end of the string to take the specified part of the string and replace it. It’s complicated when it involves a lot of information in a string Daniel’s answer solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.