I need to read a string char by char in order to perform some controls on it. Is it possible to do that? Have I necessarily got to convert it to a char array?
I tried to point at single chars with string_to_control[i]
and then increase i to move, but this doesn't seem to work.
As an example, I post a piece of the code for the control of parenthesis.
bool Class::func(const string& cont){
const string *p = &cont;
int k = 0;
//control for parenthesis
while (p[k].compare('\0') != 0) {
if (p[k].compare("(") == 0) { ap++; };
if (p[k].compare(")") == 0) { ch++; };
k++;
};
//...
};
The string is copied alright, but as soon as I try the first comparison an exception is thrown.
EDIT: I add that I would like to have different copies of the initial string cont (and move on them, rather than on cont directly) in order to manipulate them (later on in the code, I need to verify that certain words are in the right place).
To read a character in Java, we use next() method followed by charAt(0). The next() method returns the next token/ word in the input as a string and chatAt() method returns the first character in that string. We use the next() and charAt() method in the following way to read a character.
The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search.
This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.
A string or array of characters is terminated by a null character '\0'.
The simplest way to iterate through a string character by character is a range-for:
bool Class::func(const string& cont){
for (char c : cont) {
if (c == '(') { ap++; }
if (c == ')') { ch++; }
}
//...
};
The range-for syntax was added in C++11. If, for some reason, you're using an old compiler that doesn't have C++11 support, you can iterate by index perfectly well without any casts or copies:
bool Class::func(const string& cont){
for (size_t i = 0; i < cont.size(); ++i) {
if (cont[i] == '(') { ap++; }
if (cont[i] == ')') { ch++; }
}
//...
};
If you just want to count the opening and closing parentheses take a look at this:
bool Class::func(const string& cont) {
for (const auto c : cont) {
switch (c) {
case '(': ++ap; break;
case ')': ++ch; break;
}
}
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With