-1

Hello,

I cannot seem to find a past question on this topic so I took it upon myself to ask firsthand.

Here I have a string that I would like to read:

1234567890123456789012345678901234567890

For each time that the number 4 is displayed, I would like to add a 2 to the string

Could I get some help? ( I am newer to C# so if there is an easy way that I am missing to do this please inform me )

I would like my code to be somewhat formatted like this:

class findEach()
{
    public void find(string? myString)
    {
        foreach (index in myString)
        {
            insert.atIndex("2");
        }
    }
}

Any help will be highly appreciated

WillDevv12
  • 33
  • 4
  • 1
    Please see [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/q/284236/328193) You are encouraged to make an attempt. If during your attempt you encounter a specific problem, such as a specific operation producing an error or an unexpected result, we can help with that. To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Jun 15 '23 at 17:36
  • 2
    Having said that... If the goal is to insert a `"2"` after every `"4"` then wouldn't that simply be `myString.Replace("4", "42")` ? – David Jun 15 '23 at 17:38
  • @David Thanks for the help. I will be sure to use that next time I decide to ask a question. Also, code works perfectly, thanks. – WillDevv12 Jun 15 '23 at 18:16

1 Answers1

0

The easiest way to replace all instances of a string, in another string, with a new string, is to use the string.Replace() method.

string originalString = "1234567890123456789012345678901234567890";
string stringToReplace = "4";
string stringToReplaceWith = "42"; //This may just be 2, depending on what you want
string replacedString = originalString.Replace(stringToReplace, stringToReplaceWith);
Josh Heaps
  • 296
  • 2
  • 13