Example of what I am trying to do:
String = "This Is My Sentence"
I am looking to get this as a result: "TIMS", which takes only first letter of every word.
I am struggling with C++.
Example of what I am trying to do:
String = "This Is My Sentence"
I am looking to get this as a result: "TIMS", which takes only first letter of every word.
I am struggling with C++.
cout<<myString[0];
for(int i=0;i<(myString.size-1);i++)
{ if(myString[i]==" ")
{
cout<< myString[i+1];
{
}
I didn't checked if it compiles that way but you schould get the idea of this possible simple solution. It will only work with strings similar to your example. You should take a look at the Split Method like others already suggested.
Have a look at Boost Tokenizer - the code should look somehow like this (not tested):
std::string firstLetters(const std::string& str)
{
std::string result="";
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep(" ");
tokenizer tokens(str, sep);
for (tokenizer::iterator tok_iter = tokens.begin();
tok_iter != tokens.end(); ++tok_iter)
{
if (tok_iter->size>0)
{
result+=(*tok_iter)[0];
}
}
return result;
}
Alternatively, you can also use Boost String Algorithms (again untested)
std::string firstLetters(std::string& str)
{
std::string result="";
std::vector<std::string> splitvec;
boost::split( splitvec, str, boost::is_any_of(" "), boost::token_compress_on );
//C++11: for (std::string &s : splitvec)
BOOST_FOREACH(std::string &s, splitvec)
{
if (s.size()>0)
{
result+=s[0];
}
}
return result;
}
For completeness I should mention the strtok function, but this is more C than C++ ;-)
*Jost