What is String.charAt() in Arduino
The String.charAt() function in Arduino returns the character at a specific index position of a string. This function contains one parameter which is the index position of the character that we want to get from a string.
Syntax
The syntax of String.charAt() function is:
In the above syntax, index keyword represents the position of a character in a string.
Return Type
This function gives us the character inside a string at the index number which we passed as a function parameter.
Parameter
This function contains one parameter:
index – The index position of the character we want to know. It should be a positive integer representing the position of the character in the string.
How to Use String.charAt() in Arduino
To use the String.charAt() function in Arduino, follow these steps:
- Create a string using the String class.
- Call the charAt() function on this string object.
- Pass the index position of the character that we want to know as a parameter to the charAt() function.
Below is the code that explains the usage of String.charAt() function in Arduino programming:
Serial.begin(9600);
String myString = "Linuxhint";
char myChar = myString.charAt(4);
Serial.print("Character at index 4 is: ");
Serial.println(myChar);
}
void loop() {
}
Code started by initializing serial communication in setup() function. After that, a new string variable myString with the value “Linuxhint” is defined.
The charAt() function is called on myString with an argument of 4. This will give us the characters at the 4th position inside a string. The counting for the index starts from the left and begins with the number 0. Once the character is read it will be stored in the myChar variable. In the last part of the code value of myChar is printed on the serial monitor.
The following output will appear as the fifth character of the string “Linuxhint” is “x”, so it will be printed to the serial monitor.
Note: String.charAt() function works with ASCII characters only. It cannot handle extended ASCII or Unicode characters.
Conclusion
The String.charAt() function in Arduino can give us the character at a specific position inside a string. Using this function, we can retrieve any character from a string by just passing the index number of the character as a parameter of this function. For details on syntax, parameters, and return value of this function read the article.