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