Alisinna
Alisinna

Reputation: 121

Reading character by character from a string in C

I am trying to read character by character from a string in my xcode porgram on C. Can this be done on C because I can't seem to find any function as to how to do it..

For example:

If I were to read character by character from:

char* name= "Mario";

How can this be done? Thanks so much for your help!

Upvotes: 0

Views: 117

Answers (2)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22254

There are 2 ways to iterate over null-terminated char array (string) of unknown length :

for (char *ch = name; *ch; ++ch) {
    // *ch is the current char
}

for (int i=0; name[i]; ++i) {
    // name[i] is the current char and i the index
}

If the length is not known you can get it with strlen and use it in the second for loop as a limit for i. But strlen will iterate itself over the char array to find the null terminating and that's wasteful.

Upvotes: 3

Ian Abbott
Ian Abbott

Reputation: 17513

Just index it like an array, e.g. char x = name[0]; /* sets x to 'M' */

And remember, there will be a null terminator at the end of the string. The null terminator compares equal to 0.

Upvotes: 1

Related Questions