0

I have a requirement like this: I have a string like "-myArg:ArgVal".

std::string strArg = "-myArg:ArgVal";

Now, I have to check in above string first character is always '-' and if first character is '-' i should remove it and i should store "myArg" and "ArgVal" in two different string objects.

How can I do this efficiently?

3
  • 6
    Why are you worried about "efficiency" for something like this? How often do you need to do this? It looks like a command-line argument, which tends to imply that the parsing happens very rarely. Commented Mar 29, 2011 at 13:36
  • @unwind: Efficiency can be measured in number of lines of code, or number of programmer minutes, as well as CPU time. Commented Mar 29, 2011 at 13:38
  • Better to go for clarity in this case. Initialization code can be pretty inefficient since it only runs once. Only optimize the stuff that takes the most runtime, and don't even worry about that until you get to the point where your program runs correctly and passes all tests. Commented Mar 29, 2011 at 13:40

4 Answers 4

3

Try this

if (strArg[0] == '-') {
    strVar1 = strArg.substr(1, strArg.find(':') - 1);
    strVar2 = strArg.substr(strArg.find(':') + 1);
}

Of course I'm assuming that if the string starts with '-' then there will be a ':' in it with chars before and after. You should probably check this because if there isn't it can cause an error

Sign up to request clarification or add additional context in comments.

1 Comment

add a check for empty string, strArg[0] is not guaranteed to work
1

Have a look at std::string::substr() and std::string::find().

Comments

1

The most scalable and solid way is via regular expressions. Recommended library is Boost.Regex

3 Comments

or in C++0x, std::tr1::regex or std::regex
I love regular expressions, but this is overkill for what the OP needs in this case. You're putting a picture frame on the wall with a jackhammer.
@John You can say that and you'll be right. I would go for regex because the moment you need to modify this parser, or make it more complex you'll have all you need right under your nose.
0

std::string has the functions you need. You can check the first char by using string::at and create substrings with string::substr. Erasing single chars works the same comfortable way.

See a c++ reference for more information.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.