Go to your University || Python Lab || DSA Lab || AI & Machine Learning Lab || Linux Lab || OOPs Lab || DBMS Lab || JAVA Lab ||| Free Online Tutorials
companies for Campus Placement || Logical Reasoning || Quantitative Aptitude || General English || Technical-MCQ and Interview Questions || HR Interview Questions
0 like 0 dislike
8 views
in Tutorial & Interview questions by Goeduhub's Expert (7.8k 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 (7.8k 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++;

}
 Placements:   List of companies | Logical Reasoning Questions | Quantitative Aptitude Questions | General English Questions | Technical-MCQ and Interview Questions
 Online Free Training:  MACHINE LEARNINGPython Programming | Database Management System(DBMS) | Object Oriented Programming(OOPs) using C++ | Data Structures and Algorithms(DSA) | Java Programming | Linux/Unix | C Programming
Exams: List of Exams After Graduation | List of Engineering Entrance Examinations (UG/PG) | JEE Main | JEE Advanced | GATE | IES | ISROList of PSUs
 Download Previous Year Papers For:  GATE | IES | RAJASTHAN TECHNICAL UNIVERSITY (RTU-Kota)RPSC Technical Exams | ISRO
 Goeduhub
About Us | Contact Us   Social::   |  | 

 

...