FIFA-2022 Career Guide Free Tutorials Go to Your University Placement Preparation 
0 like 0 dislike
295 views
in Tutorial & Interview questions by Goeduhub's Expert (9.3k points)

If we know the length of the string, we can use a for loop to iterate over its characters:

1 Answer

0 like 0 dislike
by Goeduhub's Expert (9.3k points)
 
Best answer
If we know the length of the string, we can use a for loop to iterate over its characters:

char * string = "hello world"; /* This 11 chars long, excluding the 0-terminator. */

size_t i = 0;

for (; i < 11; i++)

{    

printf("%c\n", string[i]);    /* Print each character of the string. */ }

Alternatively, we can use the standard function strlen() to get the length of a string if we don't know what the string is:

size_t length = strlen(string);

size_t i = 0;

for (; i < length; i++)

{    

printf("%c\n", string[i]);    /* Print each character of the string. */

}

Finally, we can take advantage of the fact that strings in C are guaranteed to be null-terminated (which we already did when passing it to strlen() in the previous example ;-)). We can iterate over the array regardless of its size and stop iterating once we reach a null-character:

size_t i = 0;

while (string[i] != '\0')

{       /* Stop looping when we reach the null-character. */    

printf("%c\n", string[i]);    /* Print each character of the string. */    

i++;

}

Learn & Improve In-Demand Data Skills Online in this Summer With  These High Quality Courses[Recommended by GOEDUHUB]:-

Best Data Science Online Courses[Lists] on:-

Claim your 10 Days FREE Trial for Pluralsight.

Best Data Science Courses on Datacamp
Best Data Science Courses on Coursera
Best Data Science Courses on Udemy
Best Data Science Courses on Pluralsight
Best Data Science Courses & Microdegrees on Udacity
Best Artificial Intelligence[AI] Courses on Coursera
Best Machine Learning[ML] Courses on Coursera
Best Python Programming Courses on Coursera
Best Artificial Intelligence[AI] Courses on Udemy
Best Python Programming Courses on Udemy

 Important Lists:

Important Lists, Exams & Cutoffs Exams after Graduation PSUs

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy ||  Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 

 

Free Online Directory

...