How to split a string in C++?

C++: How to split a string?

  • example string x = "John Smith" how do i turn that into: x1 = "John" x2 = "Smith" and then again turn that into "SmithJohn"

  • Answer:

    Unless you're using boost or another library that supports string tokenization, your best bet is to use string streams: #include <sstream> #include <iostream> #include <string> using namespace std; int main() {      string x = "John Smith";      string x1, x2;      istringstream(x) >> x1 >> x2;      string result = x2 + x1;      std::cout << result << '\n'; } online demo: http://ideone.com/vcseY note, for an outdated comiler, you may need to write      istringstream buf(x);      buf >> x1 >> x2; as in http://ideone.com/lzoXH

kung_foo... at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

you have to use a loop to traverse whole string, then compare each character with the space.. if space character is found it means you have to store next characters to next string variable.. check this example i've made for you: #include<iostream.h> #include<conio.h> #include<stdio.h> void main() { char str[2000],words[100][20]; //it can have 100 words of lentgh 20 characters int i,word_cnt=0,char_cnt=0; clrscr(); cout<<"Enter any string:"; gets(str); for(i=0;str[i]!='\0';i++) { if(str[i]!=' ') { words[word_cnt][char_cnt]=str[i]; char_cnt++; }else{ words[word_cnt][char_cnt]='\0'; char_cnt=0; word_cnt++; } } cout<<"Seprated words:"<<endl; for(i=0;i<=word_cnt;i++) { cout<<words[i]<<endl; } getch(); }

Mr. World

int i,j; char x[50]="John Smith\0", x1[25], x2[25]; i=0; while (x[i]!=' ') { x1[i]=x[i]; i++; } x1[i]='/0'; j=i+1; i=0; while (x[j]!='\0') { x2[i]=x[j]; i++; j++; } x2[i]='\0'; //now x1=John and x2=Smith i=0; j=0; while (x2[i]!='\0') { x[i]=x2[i]; i++; } while (x1[j]!='\0') { x[i]=x1[j]; i++; j++; } x[i]='\0'; // now x = SmithJohn

Vlad

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.