为了更好地理解,我们始终建议您学习下面列出的C语言编程基础主题
在此 C 程序中,我们计算给定字符串中的字符数以查找并显示字符串长度。字符串的长度表示该字符串中的字符数。例如,考虑一个字符串“powerful”,该字符串中的字符数为 8。
使用此 C 程序,我们查找字符串的长度,这意味着我们需要查找字符串中的字符数。我们需要使用“for 循环”计算字符串中的字符数,最后,我们将输出显示为计数器的值。我们声明一个数组来存储字符串,并接受用户字符串到该数组中。然后我们启动 for 循环来计算字符串字符数并显示输出。步骤如下:
for 循环计算数组中的字符数,并将结果存储在一个变量中。此处程序使用 For 循环来查找字符数。
for(initialization Statement; testExpression; updateStatement)
{
// code
}
这里初始化语句只执行一次。然后评估测试表达式。如果测试表达式为真,则执行 for 循环内的代码并更新术语。该过程一直持续到测试表达式变为假。但是如果测试表达式为假,For 循环内的代码将终止。
步骤 1:包含头文件以在 C 程序中使用内置函数。
步骤 2:声明字符数组字符串。
步骤 3:声明整数变量 I,length。
步骤 4:设置 length=0。
步骤 5:使用 gets() 函数从用户那里接受一个字符串。
步骤 6:设置 i=0。
步骤 6:通过使用条件 string[i] != '\0' 的 for 循环,将 length 增加 1。
步骤 7:将“i”增加 1,并重复步骤 6。
步骤 8:使用 printf 显示字符串的长度作为 length。
#include <stdio.h>
void main() {
char string[50];
int i, length = 0;
printf("Enter a string\n");
gets(string);
for (i = 0; string[i] != '\0'; i++) /*keep going through each */ {
/*character of the string */
length++; /*till its end */
}
printf("The length of a string is the number of characters in it\n");
printf("So, the length of %s =%d\n", string, length);
}
Enter a string hello The length of a string is the number of characters in it So, the length of hello = 5 RUN2 Enter a string E-Commerce is hot now The length of a string is the number of characters in it So, the length of E-Commerce is hot now =21