英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论