Arduino里的字符串笔记

Posted by Dapenson on April 27, 2020

Arduino里的字符串笔记

1 字符串转数字 String To Int

/*
使用String.toInt()将字符串转为数字示例
 */

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

  1. 直接赋值
String myNumber = 1234;
  1. 使用类成员函数转换,将数字自动追加到字符串结尾
int value = 123;
String myReadout = "The reading was ";
myReadout.concat(value);
  1. 使用类运算符转换,将数字自动追加到字符串结尾
int value = 123;
String myReadout = "The reading was ";
myReadout += value;

3 常见函数整理

String.c_str()
一个将string转换为 const* char的函数。
c_str函数的返回值是const char的,不能直接赋值给char

    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 三者转换

1. const char* 和string 的转换

(1) const char*转换为 string,直接赋值即可。

const char* tmp = "tsinghua"
string s = tmp;

(2) string转换为const char*,利用c_str()

string s = "Arduino";
const char*tmp = s.c_str();
2. char*和const char* 的转换

(1) const char*转化为char*,利用const_cast<char*>

const char* tmp = "Arduino";
char* p = const_cast<char*>(tmp);

(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<char*>(str.c_str());