Deacon Thomson
Deacon Thomson

Reputation: 31

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))
}

Upvotes: 1

Views: 881

Answers (1)

A M
A M

Reputation: 15277

You need to be careful with distinguishing operators = and ==. The first is the assignment operator, 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 explanations:

In many many programming languages, so called loops 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 variable 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 character 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 each character is '-' or not.

One of many many possible implementations:

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

Upvotes: 3

Related Questions