2015-10-11 50 views
0

我是C#的新手,所以這個問題(希望)會很簡單。C#字符增量

我想增加字符數組中的每個字符。這是我的代碼。

 //increment each character in array 
     for (int i = 0; i < text.Length; i++) 
     { 
      textArray[i]++; //this works 
      // textArray[i] +=13; //this doesn't work 
     } 

我能夠增加一個數組,但不能超過這個數。

謝謝!

如果有幫助,這裏是我的代碼的其餘部分。

 // put all text into a string - here loosely typed as a var 
     var s = System.IO.File.ReadAllText(@"C:\Users\Eliezer Feder\Documents\2 Landers\Limudie Chol\5th Semester\C#\GettysburgAddress.txt"); 

     var upper = s.ToUpper(); 

     string text = ""; //empty string to add characters to it if they are indeed characters. 
     foreach (char c in upper.ToCharArray()) 
     { 
      if (Char.IsLetter(c)) 
      { 
       text += c; 
      } 
     } 

     //change the 'text' string to an array so can increment each individual char 
     Char[] textArray = text.ToArray(); 

     //output old text in the char array: 
     Console.WriteLine(textArray); 
     Console.ReadKey(); 

     //increment each character in array 
     for (int i = 0; i < text.Length; i++) 
     { 
      textArray[i]++; //this works 
      // textArray[i] +=13; //this doesn't work 
     } 

     Console.WriteLine(textArray); 
     Console.ReadKey(); 

     //change back to string so can write to file: 
     string lines = ""; //empty string to add characters to it if they are characters. 
     foreach (char c in upper.ToCharArray()) 
     { 
      lines += textArray[c]; 
     } 


     System.IO.File.WriteAllLines(@"Eliezer Feder\Documents\2 Landers\Limudie Chol\5th Semester\C#\encrypted.txt", lines); //THIS PART IS ALSO NOT WORKING FOR SOME REASON 
+1

你是什麼意思它不工作?你有例外嗎?你的期望是什麼? –

+0

請參閱http://www.dotnetperls.com/rot13 – nozzleman

+0

始終包含完整的錯誤消息(來自異常或編譯器)和谷歌。副本在標題中使用它。 –

回答

2

類型的textArray元素是char。文字13類型爲int。將int添加到char的結果是int,因此您無法將其分配給char變量。

你必須投字面來char,那麼結果也將是一個char

textArray[i] += (char)13;