替換 Arduino 中字串中的字元


Arduino 中的.replace() 函式允許你在 Arduino 中用另一個字元/子串替換一個字元或子串。

注意此函式替換原字串中的子串,不會返回包含更改內容的新字串。

下面的程式碼中給出了示例 -

示例

void setup() {
   Serial.begin(9600);
   Serial.println();
   String s1 = "Hello World";
   Serial.println(s1);
   s1.replace('e','a');
   Serial.println(s1);
   
   s1 = "Hello World";
   s1.replace("ll","gg");
   Serial.println(s1);

   s1 = "Hello World";
   s1.replace("li","gg");
   Serial.println(s1);
}
void loop() {
   // put your main code here, to run repeatedly:
}

序列監視器的輸出如下 -

輸出

如你所見,在最後一次嘗試中,字串沒有改變。這是因為子串 'li' 不是 s1 的一部分。因此,沒有要替換的!

更新日期: 24-Mar-2021

6K+ 瀏覽

開啟您的 職業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.