Go Down

Topic: Use substring from right (Read 338 times) previous topic - next topic

smallpoul

Probaby a stupid question but how to use this fonction but from the right? in some language you just have to use the minus but it seems not to work with the substring.
Code: [Select]
String test = 12345688
I want to slipt the string from the last 2 digit, so 123456 and 88. The length of the string may vary so that why i want to go from the right so it will alway be the 2 last digit that will be split. I saw on the forum that it could maybe be achived by dtostrf() but didn't saw a good explanation. And for sure i want to keep this in String
Thanks

PaulS

Quote
The length of the string may vary

But is not unknown. Use length-2 as the start of the substring.

zoomkat

You can get the length of the string, then get the last two characters.

http://arduino.cc/en/Reference/StringLength

http://arduino.cc/en/Tutorial/StringSubstring
Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   8)

smallpoul

You are right, thanks for the tips,
I use:
Code: [Select]
int length = myString.length();
To determinate the length and after that it was a piece of cake.
Thanks again

zoomkat

Maybe a shorter way without having to get the length separately.

Code: [Select]

// zoomkat 9-24-13 serial I/O string test
// type a string in serial monitor. then send or enter

String readString, newString;

void setup() {
  Serial.begin(9600);
  Serial.println("serial test 0021"); // so I can keep track of what is loaded
}

void loop() {

  while (Serial.available()) {
    delay(2);  //delay to allow byte to arrive in input buffer
    char c = Serial.read();
    readString += c;
  }

  if (readString.length() >0) {
    Serial.println(readString);
    //Serial.println(readString.length());
    newString = readString.substring(readString.length() - 2, readString.length());
    Serial.println(newString);
    newString="";
    readString="";
  }
}

Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   8)

Go Up