用变量字符串替换字符串中的单个字符?

时间:2016-12-07 17:05:48

标签: c# string methods

问过上一个问题并没有真正问我想知道什么,并且没有深思熟虑所以这是一个新问题,我想用不同的字符替换用户输入字符串中的特定字符,如替换带“w”的所有“a”实例。我需要声明一个能够使这个工作的方法。我被困了,因为我不知道该怎么做。我知道我希望它找到角色并替换它们,但我不知道如何去做。这就是我到目前为止所做的:

public static void Encrypt(string args)
{


} 

public static void Decrypt(string args)
{


}

static void Main(string[] args)
{

     Console.WriteLine("Enter string to be encrypted or decrypted");
     string words = Console.ReadLine();
     Console.WriteLine("Enter 1 to encrypt or enter 2 to decrypt");
     string EnOrDec = Console.ReadLine();
     int answer = Convert.ToInt16(EnOrDec);
     if (answer == 1)
     {
         Encrypt(words);                
     }
     if (answer == 2)
     {
         Decrypt(words);
     }

   }
}

我尝试使用此处找到的替换方法:https://msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx但它给了我错误,我不确定这是我想要的。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

试试这个示例代码:

      string text = "ABCABCABCABC";
      text=text.Replace("A", "W");

答案 1 :(得分:0)

words.Replace("a", "w")

将产生所需的String。执行此操作的方法看起来像

public String myReplace(input, what, withWhat) {
    return input.Replace(what, withWhat);
}

你可以这样称呼它:

myReplace(words, "a", "w")

如果您打算手动执行此操作,则可以执行以下操作:

public String myReplace(input, what, withWhat) {
   while (input.indexOf(what) >= 0) {
       input = input.Substring(0, input.IndexOf(what)) + withWhat + input.Substring(input.IndexOf(what) + what.length);
   }
   return input;
}
相关问题