I am trying to write a program that will return words that start with the symbol # from a string. For example: A string such as "I like #tacos and #pizza" would return: #tacos #pizza
This is my current code:
int main(void){
string myString = "I like #tacos and #pizza";
std::istringstream iss(myString);
while(iss >> myString){
int i = 0;
if(myString[i] == '#'){
iss >> myString;
}
i++;
}
std::cout << myString;
}
However, this only returns one word that starts with a hashtag. Any help as to what I can change in the code?
You just need to check the string's first character with front
or myString[0]
, and print the output in the loop. Your original code will at most print once so I move the print statement into the loop.
#include <iostream>
#include <sstream>
#include <string>
int main(void) {
std::string myString = "I like #tacos and #pizza";
std::istringstream iss(myString);
while (iss >> myString) {
if (myString.front() == '#') {
std::cout << myString << std::endl;
}
}
return 0;
}