CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2008
    Posts
    7

    Question 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!

  2. #2
    Join Date
    Jan 2009
    Posts
    1,689

    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);

  3. #3
    Join Date
    Feb 2009
    Posts
    326

    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
  •  





Click Here to Expand Forum to Full Width

Featured