如何在c#win中同时使用2替换功能。形成 [英] How to use 2 Replace Function at same time in c# win. form

查看:70
本文介绍了如何在c#win中同时使用2替换功能。形成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我有一个独特的要求,我将以一个例子来解释



My String

Today i have a unique requirement which i am going to explain with an example

My String

string s = "aaaabcc";



现在我想同时使用2个替换函数。所以答案是这样的: -

输出


Now i want to use 2 replace functions at same time. so, answer would be like this:-
OUTPUT

ccccbaa



直到现在我不知道怎么开始,因为我写的时候


Till now i don't know how to start as when i write

string s = "aaaabcc";
s = s.Replace("a","c").Replace("c","a");



答案出错导致最后replace函数删除新添加的char。

任何人都可以帮我这里任何代码片段都会有所帮助







提前谢谢


the answer goes wrong cause last replace function removes the newly added char.
Can anyone help me here any piece of code snippet would be helpful



Thanks in advance

推荐答案

因为你要替换相同的字符,所以你应该使用临时字符:

Since you are replacing the same chars then you should use a temp char:
string s = "aaaabcc";
s = s.Replace("a","x");
s = s.Replace("c","a");
s = s.Replace("x","c");





编辑:

使用以下代码:




Use the following code:

string s = "aaaabcc";
StringBuilder sb = new StringBuilder();
foreach(var c in s)
{
    if(c == 'a')
        sb.Append('c');
    else if(c == 'c')
        sb.Append('a');
    else
        sb.Append(c);
}
string outs = sb.ToString();


这篇关于如何在c#win中同时使用2替换功能。形成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆