/*
使用String.toInt()将字符串转为数字示例
*/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | String inString = ""; // string to hold input void setup() {<!-- --> // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) {<!-- --> ; // wait for serial port to connect. Needed for native USB port only } // send an intro: Serial.println("\n\nString toInt():"); Serial.println(); } void loop() {<!-- --> // Read serial input: while (Serial.available() > 0) {<!-- --> int inChar = Serial.read(); if (isDigit(inChar)) {<!-- --> // convert the incoming byte to a char // and add it to the string: inString += (char)inChar; } // if you get a newline, print the string, // then the string's value: if (inChar == '\n') {<!-- --> Serial.print("Value:"); Serial.println(inString.toInt()); Serial.print("String: "); Serial.println(inString); // clear the string for new input: inString = ""; } } } |
2 数字转字符串 IntTo String
直接赋值
String myNumber = 1234;
使用类成员函数转换,将数字自动追加到字符串结尾
int value = 123;
String myReadout = "The reading was ";
myReadout.concat(value);
使用类运算符转换,将数字自动追加到字符串结尾
int value = 123;
String myReadout = "The reading was ";
myReadout += value;
3 常见函数整理
String.c_str()
一个将string转换为 const* char的函数。
c_str函数的返回值是const char的,不能直接赋值给char
1 2 | String s = "Chelse"; const char *str = s.c_str(); |
strcpy
原型声明:char strcpy(char dest, const char *src);
strcpy(A, B.c_str());//将B复制给A
sprintf
把整数123 打印成一个字符串保存在s 中。
char s;
sprintf(s, “%d”, 123); //产生"123"
4 char,const char*和string 三者转换
- const char* 和string 的转换
(1) const char*转换为 string,直接赋值即可。
const char* tmp = “tsinghua”
string s = tmp;
(2) string转换为const char*,利用c_str()
string s = “Arduino”;
const chartmp = s.c_str();
2. char和const char* 的转换
(1) const char转化为char,利用const_cast
const char* tmp = “Arduino”;
char* p = const_cast
(2) char转化为const char,直接赋值即可。
char* p = “tsinghua”
const char* tmp = p;
3. char和string 的转换
有了1和2的基础,char和string转化就很简单了。
(1)char*转化为string,直接赋值即可。
char* p = “Arduino”
string str = p;
(2)string转化为char*,走两步,先是string->const char,然后是const char->char*
string str = “Arduino”;
char* p = const_cast