I need to check whether an std:string begins with "xyz". How do I do it without searching through the whole string or creating temporary strings with substr().
Thanks.
I need to check whether an std:string begins with "xyz". How do I do it without searching through the whole string or creating temporary strings with substr().
Thanks.
I feel I'm not fully understanding your question. It looks as though it should be trivial:
s[0]=='x' && s[1]=='y' && s[2]=='z'
This only looks at (at most) the first three characters. The generalisation for a string which is unknown at compile time would require you to replace the above with a loop:
// look for t at the start of s
for (int i=0; i<s.length(); i++)
{
if (s[i]!=t[i])
return false;
}
Look to the Boost's String Algo library, that has a number of useful functions, such as starts_with, istart_with (case insensitive), etc. If you want to use only part of boost libraries in your project, then you can use bcp utility to copy only needed files
I am really fed up when people demands : " I want to fly up to London but I don't want to use an airplane, neither a rocket and I even don't want to be transformed into a bird."
When I ask them "Any particular reason?", they say: "Airplane will burn a lot of fuel and cause pollution, the rocket is too fast for me and I don't want to loose my human-ship". These are the symptoms of pre-mature optimization and as Donald Knuth beautifully puts up
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."
So, in a nutshell, please tell us "What you want to achieve" and not "How you want to achieve".
There is nothing wrong in using substr and string comparisons, so why not use it.
I would use compare method:
std::string s("xyzblahblah");
std::string t("xyz")
if (s.compare(0, t.length(), t) == 0)
{
// ok
}
if (mystring.find("xyz", 0) == 0)
{
// you found it
}
else
{
// you didn't find it, or it doesn't start with xyz
}