Arduino strcmp 函式

Ammar Ali 2023年10月12日 Arduino Arduino String
Arduino strcmp 函式

在本教程中,我們將討論使用 Arduino 中的 strcmp() 函式比較兩個字串。

Arduino strcmp() 函式

strcmp() 函式比較 Arduino 中的兩個字串。strcmp() 函式比較兩個字串中存在的字元的 ASCII 值,然後根據字元的 ASCII 值返回三種型別的輸出值。

鍵盤上的字元具有唯一的 ASCII 值,例如字元 a 的 ASCII 值是 65。下面是 strcmp() 函式的基本語法。

output = strcmp(string1, string2);

如果兩個字串中存在的所有字元都相同,上述語法將返回 0,如果第一個字串中與第二個字串的字元不匹配的字元具有較低的 ASCII 值,則返回負數大於第二個字串中的字元,如果第一個字串的不匹配字元的 ASCII 值大於第二個字串的字元,它將返回一個正數。

如果前兩個字元的 ASCII 值差為零,則 strcmp() 函式將移動到下一個字元,以此類推,當所有字元都比較完畢後,它也將返回 0,這將表示兩個字串相等。

如果兩個字元的 ASCII 值不等於 0,函式將停止,返回當前不匹配字元的 ASCII 值之差。

例如,讓我們定義兩個相同的字串並使用 Arduino 中的 strcmp() 函式進行比較。

請參閱下面的程式碼。

int output;
void setup() {
  char* string1 = "hello";
  char* string2 = "hello";
  output = strcmp(string1, string2);
  Serial.begin(9600);
  Serial.println(output);
}
void loop() {}

輸出:

0

strcmp() 函式的輸入應該是一個常量字串。在上面的程式碼中,我們使用了 Arduino 的串列埠監視器來顯示 strcmp() 函式的輸出。

Serial.begin() 函式用於初始化序列監視器,Serial.println() 函式在序列監視器視窗上列印給定值。

我們還可以在條件語句中使用 strcmp() 函式的輸出,例如 if 語句來執行特定任務,例如如果輸出等於 0,我們可以在序列監視器上列印兩個字串是平等的。

我們還可以使用 Arduino 的其他函式來比較兩個字串,例如 compareTo()equals() 函式。檢視此連結瞭解有關 Arduino 中字串比較的更多詳細資訊。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

相關文章 - Arduino String