c语言用循环判断字符串长度
时间: 2023-12-02 12:03:10 浏览: 75
C 语言中,可以用循环来判断字符串的长度。我们可以通过遍历字符串中的每一个字符,直到遇到结束标志 '\0' 为止,统计字符的个数,就可以得到字符串的长度。
下面是一个例子:
```c
#include <stdio.h>
int main() {
char str[] = "hello world";
int len = 0;
while (str[len] != '\0') {
len++;
}
printf("The length of the string is %d.\n", len);
return 0;
}
```
运行该程序,输出结果为:
```
The length of the string is 11.
```
在上面的例子中,我们定义了一个字符串 `str`,然后通过循环遍历每一个字符,直到遇到结束标志 '\0' 为止,统计字符的个数,最后输出字符串的长度。
相关问题
c语言非递归判断字符串是不是回文
下面是C语言的非递归实现判断字符串是否为回文的代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, len, flag = 0;
printf("请输入一个字符串: ");
scanf("%s", str);
len = strlen(str);
for(i = 0; i < len/2; i++) {
if(str[i] != str[len-i-1]) {
flag = 1;
break;
}
}
if(flag == 1) {
printf("%s 不是回文字符串\n", str);
} else {
printf("%s 是回文字符串\n", str);
}
return 0;
}
```
这个程序首先读入一个字符串,然后计算字符串的长度。接着,使用一个循环来判断字符串是否是回文。在循环中,我们从字符串的两端开始比较字符,如果发现不相同的字符,则将 `flag` 标记为 `1`,表示这个字符串不是回文。如果循环结束后 `flag` 的值仍然是 `0`,则表示这个字符串是回文。
c语言循环存入字符串
你可以使用一个字符数组来存储字符串,并使用循环逐个读取和存储每个字符。例如:
```c
#include <stdio.h>
int main() {
char str[100];
int i;
printf("请输入字符串:");
for (i = 0; i < 100; i++) {
scanf("%c", &str[i]);
if (str[i] == '\n') {
str[i] = '\0'; // 将换行符替换为字符串结束符
break;
}
}
printf("你输入的字符串是:%s\n", str);
return 0;
}
```
在上面的代码中,我们先定义了一个长度为100的字符数组`str`,然后使用`for`循环逐个读取每个字符,并判断是否为换行符。如果是换行符,就将其替换为字符串结束符`\0`,并退出循环。最后输出输入的字符串。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)