I'm trying to convert the String to int. The first character of String will always be the non-int type. In the first case, I tried replacing the first character with '0' but each time the output was zero. In the second case, I used the remove() function and got the expected result. what went wrong in the first case? What would be the other alternatives to convert String to int efficiently?
String myString((char *)0);
byte num;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
myString.reserve(50);
//Case 1
myString = "H15";
myString[0] = 0;
num = myString.toInt();
Serial.print("Num: ");
Serial.println(num); //Num: 0
myString = "";
//Case 2
myString = "H15";
myString.remove(0, 1);
num = myString.toInt();
Serial.print("Num: ");
Serial.println(num); //Num: 15
//myString.clear();
}
void loop() {
// put your main code here, to run repeatedly:
}
No, I'm not adding 0, I'm trying to replace the myString[0] i.e.,(H) with 0 so that I'd be able to convert that String to int using toInt(). I'm using the approach which is generally used for array.
The 0 will not work because the value of zero is used to indicate the end of the text ( ASCII uses zero as the NULL character, so normally it will not appear within any text).
So, if I understand what you mean, you have a string in the form "H##" where # is a digit. You want to interpret these digits as a single integer and discard the leading 'H'.