Arduino基础 — Arduino 字符串

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
  • 1
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值