Jump to content

C++ String Manipulation

- - - - -

  • Please log in to reply
2 replies to this topic

#1
skastu01

skastu01

    Newbie

  • Members
  • PipPip
  • 27 posts
Hi - I need assistance in breaking up the following string into 2 strings separated by the comma. The user will input their lastname,firstname in the string variable and it needs to be separated into 2 strings. Then I need to provide a count for each of the characters in each string. Any suggestions?

This is how the user's name will be stored:

#include <string>
#include<iostream>
using namespace std;

int main () {
string name;

cout<<"Please enter your name in the form: lastname,firstname \n";
cin>>name;

return 0;
}

#2
kmhosny

kmhosny

    Programmer

  • Members
  • PipPipPipPip
  • 133 posts
you can use the find function provided in string, to search for the index of the comma then make to sub strings one 0 to comma position -1 and the other from the comma +1 to the end.
find returns the position of the character if found else it returns a value = to string::npos.
int location = name.find(",",0);//start search from 0
if(location != string::npos) // do what u want

"Recursion is just a line of code"
-Karim Hosny-
My flickr

#3
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1

#include <iostream>

#include <string>


using namespace std;


int main() {


  string full;

  

  getline(cin, full);

  

  string last(full.substr(full.find(",") + 2)); // 2 = 1 for comma and 1 for space

  

  string first(full, 0, full.find(","));

  

  cout << last << endl;

  cout << first << endl;

  

  return 0;

}


More read here and here.
A conclusion is where you got tired of thinking.
#define class struct    // All is public.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users