Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string.substr() function?

I want to make a program that will read some number in string format and output it like this: if the number is 12345 it should then output 12 23 34 45 . I tried using the substr() function from the c++ string library, but it gives me strange results - it outputs 1 23 345 45 instead of the expected result. Why ?

#include <iostream> #include <string> #include <cstdlib> using namespace std; int main(void) {     string a;     cin >> a;     string b;     int c;      for(int i=0;i<a.size()-1;++i)     {         b = a.substr(i,i+1);         c = atoi(b.c_str());         cout << c << " ";     }     cout << endl;     return 0; } 
like image 441
VaioIsBorn Avatar asked Mar 19 '10 14:03

VaioIsBorn


People also ask

What is the use of substr () in string?

The substring() method extracts characters, between two indices (positions), from a string, and returns the substring. The substring() method extracts characters from start to end (exclusive).

How do you use substr method?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.

What substring () and substr () will do?

The difference between substring() and substr() The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .

How do you substring a string in C++?

Substring in C++ A function to obtain a substring in C++ is substr(). This function contains two parameters: pos and len. The pos parameter specifies the start position of the substring and len denotes the number of characters in a substring.


1 Answers

If I am correct, the second parameter of substr() should be the length of the substring. How about

b = a.substr(i,2); 

?

like image 119
Ghislain Fourny Avatar answered Sep 21 '22 18:09

Ghislain Fourny