Pages: [1]   Go Down
Author Topic: Use substring from right  (Read 185 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Jr. Member
**
Karma: 0
Posts: 67
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 548
Posts: 46029
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
The length of the string may vary
But is not unknown. Use length-2 as the start of the substring.
Logged

0
Offline Offline
Tesla Member
***
Karma: 114
Posts: 8913
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

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

Offline Offline
Jr. Member
**
Karma: 0
Posts: 67
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

0
Offline Offline
Tesla Member
***
Karma: 114
Posts: 8913
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:
// 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="";
  }
}

Logged

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

Pages: [1]   Go Up
Jump to: