2013-04-21 95 views
0
using System; 
    using System.Collections.Generic; 
    using System.ComponentModel; 
    using System.Data; 
    using System.Drawing; 
    using System.Linq; 
    using System.Text; 
    using System.Windows.Forms; 
    using System.Globalization; 

    namespace Project_Scorps_1 
    { 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Convert_Click(object sender, EventArgs e) 
     { 
      string s = textBox1.Text; 
      char [] c = new char [s.Length]; 
      for (int i = 0; i < s.Length; i++) 
      { 
       if (i % 2 == 0) 
       { 
        (s[i].ToString()).ToUpper(CultureInfo.InvariantCulture); 
       } 

       if (i % 2 != 0) 
       { 
        (s[i].ToString()).ToLower(); 
       } 
      } 

      textBox2.Text = s; 
     } 
    } 
} 

這是我迄今爲止的代碼。 textBox1是您輸入傳票的文本框,而textbox2是包含輸出的框。C# - 將常規文本轉換爲TeXt的程序的程序

它給我輸出的是我輸入的同一個句子!

回答

3

這是因爲字符串是immutable該值被認爲是不可變的,因爲一旦通過附加,刪除,替換或插入字符創建該值,就可以*不*修改該值。。然而,什麼可以做,就是利用現有的字符串(或字符字符串中),以建立一個新的字符串:

string result = string.Empty; 
string s = textBox1.Text; 
char[] c = new char[s.Length]; 
for (int i = 0; i < s.Length; i++) 
{ 
    if (i % 2 == 0) 
    { 
     result += (s[i].ToString()).ToUpper(CultureInfo.InvariantCulture); 
    } 

    if (i % 2 != 0) 
    { 
     result += (s[i].ToString()).ToLower(); 
    } 
} 

textBox2.Text = result; 

創建每次追加一個字符可以是一個相當昂貴的操作時間一個新的字符串。如果你的輸入相當長,你應該考慮使用StringBuilder。您可以閱讀有關StringBuilderhere的更多信息。

此外,您不需要計算兩次模數,您可以改爲使用if..else

+0

你只會在每次迭代時爲's'指定一個字符。 – Femaref 2013-04-21 16:19:48

0

這可能是使用LINQ

的幫助較短
string s = "This Kind Of Text"; 

var newstr = String.Join("", s.Select((c, i) => i % 2 == 0 
           ? char.ToLower(c, CultureInfo.InvariantCulture) 
           : char.ToUpper(c, CultureInfo.InvariantCulture))); 
1

字符串是不可變的 - 你不能改變它們。你需要有一個單獨的變量來保存你的結果:

string result = ""; 
for (int i = 0; i < s.Length; i++) 
{ 
    if (i % 2 == 0) 
    { 
     result += (s[i].ToString()).ToUpper(CultureInfo.InvariantCulture); 
    } 

    if (i % 2 != 0) 
    { 
     result += (s[i].ToString()).ToLower(); 
    } 
} 

textBox2.Text = result; 
+0

非常好,ty :) – Scorps 2013-04-21 16:26:45