Online Courses
Free Tutorials  Go to Your University  Placement Preparation 
Goeduhub's Online Courses @ Udemy in Just INR 570/-
Online Training - Youtube Live Class Link
0 like 0 dislike
152 views
in Tutorial & Interview questions by Goeduhub's Expert (8.3k points)

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

Goeduhub's Top Online Courses @Udemy

For Indian Students- INR 360/- || For International Students- $9.99/-

S.No.

Course Name

 Coupon

1.

Tensorflow 2 & Keras:Deep Learning & Artificial Intelligence

Apply Coupon

2.

Natural Language Processing-NLP with Deep Learning in Python Apply Coupon

3.

Computer Vision OpenCV Python | YOLO| Deep Learning in Colab Apply Coupon
    More Courses

1 Answer

0 like 0 dislike
by Goeduhub's Expert (8.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++;

}

3.3k questions

7.1k answers

394 comments

4.6k users

 Goeduhub:

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