Best alternatives to convert String to int efficiently

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:

}

myString[0] = 0; <<<< What's that? You want to add a 0 to the end of the String? Use myString.concate( "0" );

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.

That's not going to work.

See String() - Arduino Reference

remove() - Arduino Reference

replace() - Arduino Reference

A String is not a string.

Did you mean
myString[0] = '0';
?

Why not just start the conversion one character on from the start?
Why use String at all?

1 Like

Maybe this will help...

String input = "H15";
String tmp = input.substring(1);

int number = atoi(tmp.c_str());

//number should now contain 15

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'.

To quote @TheMemberFormerlyKnownAsAWOL,

Try something like:

char input_buffer[] = "H15";
char output_buffer[20]; // big safety margin

sprintf (output_buffer, "Num: %d\n", atoi (input_buffer + 1));
Serial.print(output_buffer);

If you want DOS-style line endings (emulating the behaviour of Serial.println()), add a (sigh!) '\r' before the newline.

Bye bye String class...