簡體   English   中英

用新的字符串替換字符串的每個字符

[英]Replace each character of string with new character string

我正在開發的c#程序會檢查用戶輸入的第一個字符,以及是否以開頭. (點)我想在用戶書寫時用和平的字符串替換用戶輸入的每個字符,但出現錯誤

索引超出范圍異常

我的代碼:

if (textBox1.Text.StartWith(".")) {
    string MyText = "Hello World";
    int x = 0;
    string NewText;
    while (x <= MyText.Length) {
        NewText = textBox1.Text.Replace(textBox1.Text[x], MyText[x]);
        TextBox1.Text = NewText;
        x++;
    }
}

您超出了字符串的界限,請替換:

while (x <= MyText.Length) {

while (x < MyText.Length) {
while(x < MyText.Length)

要么

while(x <= MyText.Length - 1)

如果數組的長度為x,則其最后一個索引為x-1,因為數組從0索引開始

如果我理解正確(沒有問題的樣本),我建議使用straitforward的Linq 嘗試使用模塊化算術 - index % MyText.Length以避免索引問題

string source = ".My Secret Message for Test";
string MyText = "Hello World";

// If user input starts with dot
if (source.StartsWith("."))
  source = string.Concat(source
    .Select((c, index) => MyText[index % MyText.Length])); 

TextBox1.Text = source;

結果:

   Hello WorldHello WorldHello

首先如@ Daniell89所說:

采用

while(x < MyText.Length)

其次:您不僅將x用作MyText的索引,還將x用作textBox1.Text的索引。 因此,您需要檢查它是否足夠長。

您可以執行以下操作:

while (x < Math.Min(MyText.Length, textBox1.Text.Length)
{
    NewText = textBox1.Text.Replace(textBox1.Text[x], MyText[x]);
    TextBox1.Text = NewText;
    x++;
}

但是我認為最好在這里進行陳述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM