This question already has answers here:
How to replace all occurrences of a character in string?
(17 answers)
Closed 4 years ago.
I've tried:
versionString = versionString.replace(versionString.begin(), versionString.end(), '(' , '-' );
The result is: "--------------". Basically replacing all the characters. What is that?
versionString is a basic string.
If you look at e.g. this std::string::replace reference you will see that there's no overload that takes the arguments you pass. Something the compiler really should warn you about.
The closes one is number 6:
basic_string& replace( const_iterator first, const_iterator last,
size_type count2, CharT ch );
which replaces the range with count2 copies of ch.
That is, you replace your string with '(' number of dashes. With ASCII that '(' will be converted to the integer 40 (it's this conversion the compiler should have warned you about).
One solution is to repeatedly find the character you want to replace, and replace only that single character.
A much simpler solution is to use the standard algorithm function std::replace:
std::replace(begin(versionString), end(versionString), '(', '-');
Related
This question already has answers here:
comma separated expression in while loop in C
(5 answers)
How does the Comma Operator work
(9 answers)
Closed 5 years ago.
string command;
string bookName;
while (cin >> command, command != "END")
{...}
Here in while loop's condition, there is a comma.
I know that multiple conditions can be added using && or ||.
But why use ,?
Is there any certain benefits? Can you please explain the usage and syntax?
It's the comma operator, also known as the "evaluate and forget" operator. The effect of a, b is:
Evaluate a, including any side effects
Discard its value (i.e. do nothing with it)
Evaluate b
Use the result of b as the result of the entire expression a, b
The author of the loop wanted to express the following:
Read command from cin, and then enter the loop body unless command is equal to "END"
However, they would have been better off using && instead of , here, because cin >> command can fail (i.e. if the end of input is reached before the word END is found). In such case, the condition with , will not do what was intended (it will likely loop forever, as command will never receive the value END), while the condition with && would do the right thing (terminate).
This question already has answers here:
Get the last element of a std::string
(4 answers)
Closed 7 years ago.
In python you can say print "String"[-1] and it would print be the last character, 'g'. Is there an equivalent for this in c++?
You can use string.back() to get a reference to the last character in the string. The last character of the string is the first character in the reversed string, so string.rbegin() will give you an iterator to the last character.
Use the back() function for std::string:
std::string str ("Some string");
cout << str.back()
Output:
g
For C strings, it is
String[strlen(String) - 1];
For C++ style strings, it is either
String.back();
*String.rbegin();
String[String.length() - 1];
You can use the function:
my_string.back();
If you want to output it, then:
#include <iostream>
std::cout << my_string.back();
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I wanna create a function that receive 3 string-type parameters s,oldval,newval,using iterator,insert and erase to replace the oldval in s by newval.
When I compiler it,comes the error :no match for the operator == in....
string &foo(string &s,string &oldval,string &newval)
{
string::iterator it=s.begin();
while(it!=s.end())
{
if(*it==oldval)
{
it=s.erase(it);
it=s.insert(it,newval);
}
++it;
}
return &s;
}
it is iterating over the characters of the string; *it is a single character. You can compare that with another character, but not with a string.
Either oldval and newval should have type char, not string; or you need more complicated logic to look for and replace substrings, rather than single characters, in the input. The member functions find and replace might be helpful for that.
Note that replacing a single character is as simple as *it = newval;, with no need to mess around erasing and inserting characters.
A string iterator "points" to a type of char (the template parameter for std::basic_string that makes up the std::string type), but you're comparing that character to a string (oldval) using ==.
std::string doesn't have an overload comparison operator for char.
Viktor,
I have seen your question.
"s" is a string. Wenn you use pointer,pointer only points a character. That means, just one character is selected. How can you compare a character with a string? Compiler will tell you,
"no match for the operator == in..." .
You need to view the website:
http://www.cplusplus.com/reference/string/string/find/
Best regards
Dehlen Zhang
This question already has an answer here:
std::stringstream strange behaviour
(1 answer)
Closed 9 years ago.
I have a string with lots of different characters similar to: "$: " "213.23453"
How do i extract the double value 213.23453 and store it in a variable, it's C++/C and i cant use lambdas.
You can use "poor man's regex" of the sscanf function to skip over the characters prior to the first digit, and then reading the double, like this:
char *str = "\"$: \" \"213.23453\"";
double d;
sscanf(str, "%*[^0-9]%lf", &d);
Note the asterisk after the first percentage format: it instructs sscanf to read the string without writing its content into an output buffer.
Here is a demo on ideone.
Use a regular expression.
[$]?[0-9]*(\.)?[0-9]?[0-9]?
This should match those with a $ sign and those without.
Boost.Regex is a very good regular expression library
Personally, I find Boost.Xpressive much nicer to work with. It is a header-only library and it has some nice features such as static regexes (regexes compiled at compile time).
If you're using a C++11 compliant compiler, use std::regex unless you have good reason to use something else.
Pure C++ solution could be to manually cut off the trash characters preceding the number (first digit identified by std::isdigit) and then just construct a temporary istringstream object to retrieve the double from:
std::string myStr("$:. :$$#&*$ :213.23453$:#$;");
// find the first digit:
int startPos = 0;
for (; startPos < myStr.size(); ++startPos)
if (std::isdigit(myStr[startPos])) break;
// cut off the trash:
myStr = myStr.substr(startPos, myStr.size() - startPos);
// retrieve the value:
double d;
std::istringstream(myStr) >> d;
but C-style sscanf with appropriate format specified would suffice here as well :)
This question already has answers here:
How does the Comma Operator work
(9 answers)
Closed 9 months ago.
I came across unexpected (to me at least) C++ behavior today, shown by the following snippit:
#include <iostream>
int main()
{
std::cout << ("1", "2") << std::endl;
return 0;
}
Output:
2
This works with any number of strings between the parentheses. Tested on the visual studio 2010 compiler as well as on codepad.
I'm wondering why this compiles in the first place, what is the use of this 'feature'?
Ahh, this is the comma operator. When you use a comma and two (or more) expressions, what happens is that all expressions are executed, and the result as a whole is the result of the last expression. That is why you get "2" as a result of this. See here for a bigger explanation.
It's called the comma operator: in an expression x, y, the compiler
first evaluates x (including all side effects), then y; the results
of the expression are the results of y.
In the expression you cite, it has absolutely no use; the first string
is simply ignored. If the first expression has side effects, however,
it could be useful. (Mostly for obfuscation, in my opinion, and it's
best avoided.)
Note too that this only works when the comma is an operator. If it can
be anything else (e.g. punctuation separating the arguments of a
function), it is. So:
f( 1, 2 ); // Call f with two arguments, 1 and 2
f( (1, 2) ); // Call f with one argument, 2
(See. I told you it was good for obfuscation.)
Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.
For example, the following code:
a = (b=3, b+2);
Ref:http://www.cplusplus.com/doc/tutorial/operators/
The result of the comma (",") is the right subexpression.
I use it in loops over stl containers:
for( list<int>::iterator = mylist.begin(), it_end = mylist.end(); it != it_end; ++it )
...
The comma operator evaluates the expressions on both sides of the comma, but returns the result of the second.