- #include <stdio.h>
- #include <string.h>
- int main ()
- {
- char str[] ="- This, a sample string.";
- char * pch;
- printf ("Splitting string \"%s\" into tokens:\n",str);
- pch = strtok (str," ,.-");
- while (pch != NULL)
- {
- printf ("%s\n",pch);
- pch = strtok (NULL, " ,.-");
- }
- return 0;
- }
- #include <iostream>
- #include <sstream>
- #include <string>
- using namespace std;
- int main()
- {
- string s("Somewhere down the road");
- istringstream iss(s);
- do
- {
- string sub;
- iss >> sub;
- cout << "Substring: " << sub << endl;
- } while (iss);
- return 0;
- }
- std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
- std::stringstream ss(s);
- std::string item;
- while(std::getline(ss, item, delim)) {
- elems.push_back(item);
- }
- return elems;
- }
- std::vector<std::string> split(const std::string &s, char delim) {
- std::vector<std::string> elems;
- return split(s, delim, elems);
- }
- #include <vector>
- #include <string>
- #include <sstream>
- using namespace std;
- int main()
- {
- string str("Split me by whitespaces");
- string buf; // Have a buffer string
- stringstream ss(str); // Insert the string into a stream
- vector<string> tokens; // Create vector to hold our words
- while (ss >> buf)
- tokens.push_back(buf);
- }
源地址:http://ghostjay.blog.51cto.com/2815221/927439