I am programming a kernel in C for a custom operating system that I'm making and I was wondering how I could loop for every character in a const char*
and then use if
operators to identify a character in the const char*
to run specific code.
Asked
Active
Viewed 172 times
0

Matthew G.
- 79
- 7
-
1Does this answer your question? [How to iterate over a string in C?](https://stackoverflow.com/questions/3213827/how-to-iterate-over-a-string-in-c) – Tsyvarev Mar 19 '22 at 18:05
-
@Tsyvarev Not exactly – Matthew G. Mar 19 '22 at 18:17
-
1Could you elaborate? You want to iterate over string, and the referenced question asks about that. You don't ask how to put `if` clause into the each iteration, do you? – Tsyvarev Mar 19 '22 at 18:30
-
@Tsyvarev I do, I have searched this question on google, and have found some answers where the character is stored as `"%c"`, and used inside the `printf` function, but for some reason I can't make an `if` statement to check if the string `"%c"` is equal to a specific character – Matthew G. Mar 20 '22 at 12:29
-
Do you know how strings work? – user253751 Mar 21 '22 at 18:24
1 Answers
1
how I could loop for every character in a
const char*
Like that:
const char *p;
for (p = str; *p; p++) {
// ...
}
and then use if operators to identify a character in the
const char*
to run specific code.
Inside your loop:
if (*p == 'x') { // Identify a character
// Run the specific code here
}
Or, if you want to identify a lot of characters:
switch (*p) {
case 'x':
// Run the specific code here
break;
case 'y':
// Run the specific code here
break;
// ...
}

Zakk
- 1,935
- 1
- 6
- 17