-
March 30th, 2009, 01:44 PM
#1
How to select characters in string?
So I'm working heavilly with Python right now, and one thing you can do it parse/select string pretty easily.
For example, if you wanted to create a variable and display a few letters, it'd be:
text = "Hello"
yo = text[1:4]
print yo
Output = "ell"
This seems simple, and to an extent I see it possible in C++. But all I can find is how to select a specific one character, using it like this:
string text = "Hello";
cout << text[1];
Output = "e"
But is there a way to do this selection with multiple characters, as I did in the Python example?
Thanks in advance for any help!
-
March 30th, 2009, 02:00 PM
#2
Re: How to select characters in string?
Code:
string text = "Hello World";
cout << text.substr(0, 5);
Output = Hello
substr(starting position (0 indexed), number of character);
-
March 30th, 2009, 02:11 PM
#3
Re: How to select characters in string?
string is a class defined in the STL (Standard Template Library).
This class a number of member functions defined to do string manipulation.
one of the member function is substr
substr(startingPosition, numberOfCharacters)
The string is assumed to start from the position 0, so calculate accordingly
since it is a class, it has to be invoked by the specifying the objectName.memberFunctionName();
//Sample Program, hope it helps
#include <iostream>
using namespace std;
int main()
{
string s = "Hello";
cout << s.substr(2,2);
return(0);
}
There is another way to deal with strings, using char. In this case, it is considered as an array of characters and the end of the string is marked with the character '\0'
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|