Replace in substring in C #

1

Original text:

E02000000000000002DOCE LUAMAR MORENINHA 240G                                  00100309        00100309

I need to change to this:

E02000000000000002DOCE LUAMAR MORENINHA 240G                                  20100309        20100309

I'm using this:

if (str.Substring(0, 4) == "E020")
{
    if (str.Substring(78, 2) == "00")
    {
        string str2 = str.Replace(str.Substring(78, 2), "20");

But the result is like this:

E02202020202020202DOCE LUAMAR MORENINHA 240G                                  20120309        20120309

You are placing 20 in all the places who have 00 in the line. Can anyone help me?

    
asked by anonymous 09.02.2017 / 19:51

3 answers

4

You can use the Remove method to remove a portion of string , passing as parameters the start index of the removal and how many characters you want to remove, and then use the Insert method to insert the string that you want by passing the index of where you want to insert string and string that you want to insert as parameters.

This way:

var str2 = str.Remove(78, 2).Insert(78, "20");
    
09.02.2017 / 20:03
2

This happens because the Replace method receives a value to look for and replace as the first parameter. In this parameter you pass:

str.Substring(78, 2)

Which, in this case, is 00 . In other words, you gave the program the order to change all occurrences of 00 by 20 .

If you want to change only two specific characters, in indexes 78 through 80, you can do the following:

str2 = str.Substring(0, 78) + "20" + str.Substring(80);

Or something similar.

    
09.02.2017 / 19:57
0

If the two sets of final numbers are always equal, as in the example, you can do so if you do not want to be stuck to the length of string .

    var s = "E02000000000000002DOCE LUAMAR MORENINHA 240G                                  00100309        00100309";

    string[] array = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

    s = s.Replace(array[array.Length - 1], "2" + array[array.Length - 1].Remove(0,1));

   //Retorna
             E02000000000000002DOCE LUAMAR MORENINHA 240G                                  20100309        20100309

The same works for a string of another length.

 s = "E020DOCE LUAMAR  2G        00100309   00100309";

//Retorna
      E020DOCE LUAMAR  2G        20100309   20100309
    
10.02.2017 / 11:57