Arduino 字符串
在Arduino编程中有两位字符串:
- 1、字符数组,与C语言编程使用相同
- 2、Arduino 字符串,它允许我们在代码中使用字符对象
字符串数组
字符串是一个特殊的数组,在字符串的末尾有一个额外的元素,其值总是为0(零)。这被称为“空终止字符串”,且必须以“0”结尾
void setup() {
char my_str[6];
Serial.begin(9600); // 打开串口通讯,设置传输速率为9600字节每秒
my_str[0] = 'H';
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = 0; // 必须设置结束标志0
Serial.println(my_str);
}
void loop() {
}
Serial.begin(speed) : speed 每秒传输的字节数
设置电脑与Arduino进行串口通讯时,数据的传输速率(每秒传输的字节数),常用的有:可使用以下速率:300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200。也可以根据所使用的设备设置其他传输速率。
Serial.printIn() : 可以将字符串打印到Arduino IDE的监视器窗口。
void setup() {
char my_str[] = "Hello";
Serial.begin(9600);
Serial.println(my_str);
}
void loop() {
}
编译器也可自动计算字符串数组的大小,并自动使用空值0终止字符。
操作字符串数组
void setup() {
char like[] = "I like coffee and cake"; // create a string
Serial.begin(9600);
// (1) print the string
Serial.println(like);
// (2) delete part of the string
like[13] = 0;
Serial.println(like);
// (3) substitute a word into the string
like[13] = ' '; // replace the null terminator with a space
like[18] = 't'; // insert the new word
like[19] = 'e';
like[20] = 'a';
like[21] = 0; // terminate the string
Serial.println(like);
}
void loop() {
}
输出结果
I like coffee and cake
I like coffee
I like coffee and tea
字符串对象
在Arduino编程中使用的第二种类型的字符串是字符串对象。
void setup() {
String my_str = "This is my string.";
Serial.begin(9600);
// (1) print the string
Serial.println(my_str);
// (2) change the string to upper-case
my_str.toUpperCase();
Serial.println(my_str);
// (3) overwrite the string
my_str = "My new string.";
Serial.println(my_str);
// (4) replace a word in the string
my_str.replace("string", "Arduino sketch");
Serial.println(my_str);
// (5) get the length of the string
Serial.print("String length is: ");
Serial.println(my_str.length());
}
void loop() {
}
结果:
This is my string.
THIS IS MY STRING.
My new string.
My new Arduino sketch.
String length is: 22