Extracting a suffix from a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SARAHE
    New Member
    • Feb 2007
    • 1

    Extracting a suffix from a string

    I have a C++ programming problem to extract a suffix such as Jr. or Sr. from a string that may vary each time. We are currently working with one assigned variable but I wanted to know how to code it if I have a file that would vary instead of working with a constant variable. I have the program working for the constant but I would like to know how to code for a file. The Proff. said we would have to look for the space but we would have to extract the previous spaces first???? Here is what I have:
    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    //extracts data from string
    
    int main()
    {
       string fullName = "Mike Lee Stephen, Jr";
       string fname, mname, lname, suffix;
       string position;
       position = fullName.substr(17,2);
       //*lname = fullName.substr(position, 8);
       cout << position << endl;
       return 0;
    }
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    you can search backwards from the end of a string using find_last_of() and store the suffixs in an array, e.g.
    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    //extracts data from string
    
    int main()
    {
    string fullName = "Mike Lee Stephen, Jr";
    string suffixs[]={"Jr","Sr"};
    string fname, mname, lname, suffix;
    string position;
    position = fullName.substr(17,2);
    //*lname = fullName.substr(position, 8);
    cout << position << endl;
    int index = fullName.find_last_of(suffixs[0]);
    cout << index << " " << fullName.at(index-1) << endl;
    cin.get();
    return 0;
    }
    as you read each name from the file you would need a loop to go thru the suffixs

    Comment

    Working...