C 程序:打印字符串中的字符

使用 For 循环和 while 循环编写 C 程序以使用实际示例打印字符串中的字符。

C 程序:打印字符串中的字符 示例 1

此程序允许用户输入一个字符串(或字符数组)。接下来,我们使用 While 循环来迭代字符串中的每个字符。在其中,我们使用 printf 语句打印此字符串中的字符。

/* C Program to Print Characters in a String */
#include <stdio.h>
int main()
{
    char str[100];
    int i = 0;
        
    printf("\n Please Enter any String  :  ");
    scanf("%s", str);
        
    while (str[i] != '\0')
    {
        printf("The Character at %d Index Position = %c \n", i, str[i]);
        i++;
    }
    return 0;
}
C Program to Print Characters in a String

str[] = hello

While 循环第一次迭代:while(str[i] != ‘\0’)

条件为真,因为 str[0] = h。因此,C 编程编译器将执行 printf 语句。

第二次迭代:while(str[1] != ‘\0’)

条件 while(e != ‘\0’) 为真。因此,e 将被打印

对其余While 循环迭代执行相同操作。

C 程序:显示字符串中的字符 示例 2

此字符串字符程序与上面相同。在这里,我们只是将 while 循环替换为For 循环

/* C Program to Print Characters in a String */
#include <stdio.h>
int main()
{
    char str[100];
        
    printf("\n Please Enter any String  :  ");
    scanf("%s", str);
        
    for(int i = 0; str[i] != '\0'; i++)
    {
        printf("The Character at %d Index Position = %c \n", i, str[i]);
    }
    return 0;
}
 Please Enter any String  :  python
The Character at 0 Index Position = p 
The Character at 1 Index Position = y 
The Character at 2 Index Position = t 
The Character at 3 Index Position = h 
The Character at 4 Index Position = o 
The Character at 5 Index Position = n