How to use find_first_not_of() with find() function In C++
find_first_not_of() is used to search the string for the first character that does not match any of the characters specified in the string. The find() function is used to find the first occurrence of a character.
C++
// C++ Program for Conversion // String To Vector using Delimiter // Using find_first_not_of() // with find() function #include <bits/stdc++.h> using namespace std; vector<string> split(string str, char delimiter) { vector<string> res; size_t first; size_t last = 0; while ((first = str.find_first_not_of(delimiter, last)) != string::npos) { last = str.find(delimiter, first); res.push_back(str.substr(first, last - first)); } return res; } int main() { // Delimiter is " " string s = "w3wiki is a computer science portal" ; vector<string> res = split(s, ' ' ); for ( int i = 0; i < res.size(); i++) { cout << res[i] << endl; } // Delimiter is * s = "w3wiki*is*a*computer*science*portal" ; res = split(s, '*' ); for ( int i = 0; i < res.size(); i++) { cout << res[i] << endl; } return 0; } |
Output
w3wiki is a computer science portal w3wiki is a computer science portal
C++ String to Vector Using Delimiter
Delimiters are used as separators between the characters or words in a string so that different results can get separated by the delimiter. In this article let us see the different ways in which a string with delimiters can be converted to a vector of words after getting separated by delimiters.
Example:
string x=”A B C”;
string y=”A*B*C”;
// Separate x into [‘A’,’B’,’C’] with delimiter ‘ ‘
// Separate y into [‘A’,’B’,’C’] with delimiter ‘*’
Methods that can be used to perform this operation are :
- Using find() function
- Using strtok() function
- Using getline() and stringstream
- Using find_first_not_of() with find() function
- Using regex_token_iterator