简体   繁体   中英

C++: How can I find a specific character in a string with an if? What is the "==" equivalent for strings, if there is one?

For example, I want to detect a negative in a string. I am not sure if converting the char into a const char* would work (and because doing so would be a pain because then I would not know how it would affect the rest of my code. Is there a way I can check if for any value of input[i], it "equals" a dash/negative?

#include <iostream>
#include <string>
#define LOG(x) std::cout<<x<<std::endl;
char solveBIG(std::string input) {
     for (int i = 0; i < input.size(); i += 2) {    
            if (input[i] = "-") {
            //
            }
     }

}
int main() {
    std::string example1 = {"1 2 3 - 5"};
    LOG(solveBIG(example1))
}

You need to be careful with distinguishing operators = and == . The first is for assignment and the second is the comparison operator for equality.

You mixed that up a little bit.

Now, how to detect a '-' in the string.

Solution: You will iterate over the string and compare each charcter in the string with the '-' character'.

More explantions:

In many many programming languages, so called loop s are used to execute or repeat blocks of code.

Or do iterate over "something". Therefore loops are also called Iteration statements

Also C++ has loops or iteration statements . The basic loop constructs are

Please click on the links and read the descriptions in the C++ reference. You can use any of them to solve your problem.


Additionally, you need to know that a string is a container . Container means that a varibale of such a type contains other elements from nearly any type.

A string for example, contains characters.

Example: If you have a string equivalent to "Hello", then it contains the characters 'h', 'e', 'l', 'l', 'o'.

Another nice property of some containers is, that they have an index operator or better said, a subscript operator [] . So, if you want to access a charcter in your string, you may simply use your variable name with an index specified in the subscript operator.

Very important : Indices in C++ start with 0. So the first character in a string is at index 0. Example:

std::string test = "Hello";
std::cout << test[0];

will print H

With all the above gained know how, we can now solve your problem easily. We will iterate over all characters in your string, and then check, if a character is an alphabetic charcter. In that case, we will replace it.

One of many many possible implementations:

for (int i = 0; i < input.size(); ++i) {    
    if (input[i] == "-") {
            //
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM