为每个特定字符的实例插入文本 [c#]

huangapple go评论83阅读模式
英文:

Insert text for every instance of a certain character [c#]

问题

你好,

我似乎找不到关于这个话题的过去问题,所以我决定亲自提问。

这里我有一个字符串,我想要读取:

1234567890123456789012345678901234567890

每当数字 4 被显示时,我想在字符串中添加一个 2

我能得到一些帮助吗?(我对C#相对较新,所以如果有一种我漏掉的简单方法,请告诉我)

我想我的代码格式化得像这样:

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

任何帮助将不胜感激

英文:

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

答案1

得分: 0

string.Replace()方法来替换一个字符串中所有的字符串实例,以新的字符串替代是最简单的方式。

string originalString = "1234567890123456789012345678901234567890";
string stringToReplace = "4";
string stringToReplaceWith = "42"; //这可能只是2,根据你的需求而定
string replacedString = originalString.Replace(stringToReplace, stringToReplaceWith);
英文:

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);

huangapple
  • 本文由 发表于 2023年6月16日 01:33:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76484181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定