Convert string to character array in Arduino

您所在的位置:网站首页 stringtochararray() Convert string to character array in Arduino

Convert string to character array in Arduino

#Convert string to character array in Arduino| 来源: 网络整理| 查看: 265

There are several libraries built for Arduino whose functions take in character arrays as inputs instead of strings. Thankfully, Arduino has an inbuilt method (toCharArray()) to covert a String to a Character Array. A sample implementation is given below −

Examplevoid setup() {    // put your setup code here, to run once:    Serial.begin(9600);    String s1 = "Hello World!";    char buf[30];    s1.toCharArray(buf,6);    Serial.println(buf);    s1.toCharArray(buf,s1.length());    Serial.println(buf); } void loop() {    // put your main code here, to run repeatedly: }

As you can see, the toCharArray function takes in two arguments, the array in which the characters of the strings are to be stored, and the number of characters to convert. We are initially converting only the first 5 characters of the string to a char array. Please note that we have specified 6 as the length instead of 5, because the last character is reserved for the string termination character ('0'). Thus, if you want the string to contain N characters, enter N+1 in the length argument.

This means that the first print statement will print only "Hello". In the next attempt, the entire string will get printed, as we have specified the length argument to be equal to the length of the string. But, as you can notice from the output below, the exclamation mark (!) at the end is missing. Again, this is because ideally, we should have specified the length argument to be length of the string + 1. Make sure that you don't convert more characters than what your char array can store.

The Serial Monitor output is shown below −

Output



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3