tags:

views:

148

answers:

3

How to converted string with space in double quoted string. For Example: I get string

c:\program files\abc.bat

I want to convert this string to "c:\program files\abc.bat" but only if there is space in the string.

+2  A: 

Search for white spaces. If found add \" to the front and the end of the string. That would be an escaped quotation mark.

Simon Linder
Before enclosing the string in ", search for existing " and prefix them with \. This will handle strings with " inside.
Thomas Matthews
A: 
std::string str = get_your_input_somehow();

if (str.find(" ") != std::string::npos) {
  str = "\"" + str + "\"";
}
Drew Hall
Shouldn't that be `str.find(' ') != std::string::npos)`?
Manuel
If there's the whitespace is at the beginning, 0 is returned.
KennyTM
In any case no good programing when using int as bool.
Simon Linder
@Manuel--whoops--it was too late at night--you're absolutely right! (editing now)
Drew Hall
+5  A: 

Assuming the STL string s contains the string you want to check for a space:

if (s.find(' ') != std::string::npos)
{
  s = '"' + s + '"';
}
Ton van den Heuvel
Would it be more efficient to use `'"'` instead of `"\""`?
Rupert Jones
Yes, it would be. I've edited the answer, thanks.
Ton van den Heuvel