- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert string to character array in Arduino
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 −
Example
void 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
- Related Articles
- Convert character array to string in Arduino
- Java program to convert a character array to string
- Convert string to integer/ float in Arduino
- Convert string to lowercase or uppercase in Arduino
- How do you convert a string to a character array in JavaScript?
- Convert Character Array to IntStream in Java
- Java Program to Convert Character to String
- Golang Program to Convert Character to String
- Haskell Program to Convert Character to String
- In how many ways we can convert a String to a character array using Java?
- How to convert a single character to string in C++?
- Convert integer array to string array in JavaScript?
- Convert string to char array in Java
- Convert Char array to String in Java
- Convert string to char array in C++
