c语言非递归判断字符串是不是回文
时间: 2023-07-26 19:39:29 浏览: 87
下面是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语言判断一个字符串是否为回文字符串的方法:
方法一:
```c
#include <stdio.h>
#include <string.h>
int judge();
int main() {
int i;
i = judge();
if (i == 1) {
printf("该字符串是回文。\n");
} else if (i == 0) {
printf("该字符串不是回文。\n");
}
}
int judge() {
char a[50];
int length;
int i;
gets_s(a);
length = strlen(a);
for (i = 0; i < length/2; i++) {
if (a[i] != a[length - i - 1]) {
return 0;
} else {
return 1;
}
}
}
```
方法二:
```c
#include <stdio.h>
#include <string.h>
#define N 100
int main() {
char s[N];
int i=0,j;
printf("Input a String: \n");
//输入一个字符串赋值给s
gets(s);
//j的初始值为s字符串最后一个位置
j=strlen(s)-1;
//进行while判断i、j的位置和i、j位置的值的关系
while(i<=j&&s[i]==s[j]){
//每比较一次就i右移、j左移一位
i++;
j--;
}
//判断最终i和j的的位置
//根据i、j的位置最终是会互相超越的,所以如果i<=j说明存在对应位置不等的情况就是不是回文串
if (i<=j) {
printf("不是回文字符串\n");
} else{
printf("是回文字符串\n");
}
return 0;
}
```
c语言判断多组字符串是否回文
以下是一个用C语言判断多组字符串是否回文的例子:
```c
#include <stdio.h>
#include <string.h>
int isPalindrome(char str[]) {
int len = strlen(str);
int i = 0, k = len - 1;
while (k > i) {
if (str[i++] ! str[k--]) {
return 0;
}
}
return 1;
}
int main() {
int num;
printf("Enter the number of strings: ");
scanf("%d", &num);
char str[20];
for (int i = 0; i < num; i++) {
printf("Enter a string: ");
scanf("%s", str);
if (isPalindrome(str)) {
printf("It is a palindrome\n");
} else {
printf("It is not a palindrome\n");
}
}
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)