如何用文本长度重复字符串填充字符串?

时间:2015-05-12 13:00:03

标签: c#

我的text有6个字母,key有4个字母。异或后,我只用4个字母得到newText。如何让我的key更长(重复到文字长度?

例如:string text = "flower"string key = "hell"我想让我的字符串键=" hellhe"等等......)

private string XorText(string text,string key)
        {
            string newText = "";
            for (int i = 0; i < key.Length; i++)
            {
                int charValue = Convert.ToInt32(text[i]);
                int keyValue = Convert.ToInt32(key[i]);
                charValue ^= keyValue % 33;
                 newText += char.ConvertFromUtf32(charValue);
            }
            return newText;
        }

2 个答案:

答案 0 :(得分:3)

使用remainder operator(%):

 private string XorText(string text,string key)
 {
      string newText = "";
      for (int i = 0; i < text.Length; i++)
      {
          int charValue = Convert.ToInt32(text[i]);
          int keyValue = Convert.ToInt32(key[i % key.Length]);
          charValue ^= keyValue % 33;
          newText += char.ConvertFromUtf32(charValue);
      }
      return newText;
  }

答案 1 :(得分:0)

使用StringBuilder进行字符串操作。

private string XorText(string text, string key)
{
    if (string.IsNullOrEmpty(text)) throw new ArgumentNullException("text");
    if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key");

    StringBuilder sb = new StringBuilder();

    int textLength = text.Length;
    int keyLength = key.Length;

    for (int i = 0; i < textLength; i++)
    {
        sb.Append((char)(text[i] ^ key[i % keyLength]));
    }

    return sb.ToString();
}