Replace in substring in c#

Asked

Viewed 759 times

1

Original text:

E02000000000000002DOCE LUAMAR MORENINHA 240G                                  00100309        00100309

I need to change for that:

E02000000000000002DOCE LUAMAR MORENINHA 240G                                  20100309        20100309

I’m wearing 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 coming out like this:

E02202020202020202DOCE LUAMAR MORENINHA 240G                                  20120309        20120309

You’re putting 20 everywhere who has 00 on the line. Someone can help me?

  • Those number sets you want to change are always 08 numbers and start with 00?

  • @jbueno Sorry for revert, but the position of the spaces is important and putting as quote, several spaces are rendered in HTML as one.

3 answers

4


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

Thus:

var str2 = str.Remove(78, 2).Insert(78, "20");
  • thanks helped, I got a little confused because I tbm have to change the number characters (94, 2), I had to do in 2 steps

  • @Farofakidstrader, glad I could help. If this reply of mine has been helpful and you are willing, please mark it as an answer so that you can help others as well. Thank you.

2

This happens because the method Replace receives a value to search 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 exchange all occurrences of 00 for 20.

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

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

Or something similar.

0

If the two sets of final numbers are always the same, as in the example, you can do so if you do not want to be stuck to the length of the 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 other-length.

 s = "E020DOCE LUAMAR  2G        00100309   00100309";

//Retorna
      E020DOCE LUAMAR  2G        20100309   20100309

Browser other questions tagged

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