2015-05-12 2 views
0

Мой text имеет 6 букв, мой key имеет 4 буквы. После XOR я получаю newText всего 4 буквы. Как я могу сделать мой 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; 
     } 
+1

Вместо 'key [i]' use 'key [i% key.Length]' и изменить ваш цикл 'for' для использования' i

ответ

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