编写一个c语言程序,输入字符串,判断该字符串是否对称。
时间: 2024-02-21 07:57:48 浏览: 36
好的,以下是一个判断字符串是否对称的C语言程序:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, j, len, flag = 1;
printf("请输入一个字符串:");
scanf("%s", str);
len = strlen(str);
for (i = 0, j = len - 1; i < len / 2; i++, j--) {
if (str[i] != str[j]) {
flag = 0;
break;
}
}
if (flag) {
printf("该字符串是对称的。\n");
} else {
printf("该字符串不是对称的。\n");
}
return 0;
}
```
这个程序首先输入一个字符串,然后通过循环判断字符串的前半部分和后半部分是否对称。如果对称,就输出提示信息;否则,也输出相应信息。
相关问题
用c语言编写一个算法利用顺序栈判断一个字符串是否对称串
好的,我可以为您提供这样一个算法:
1. 定义一个顺序栈,用来存储字符串中的字符。
2. 从字符串的左边开始,将每个字符依次入栈。
3. 从字符串的右边开始,依次取出每个字符,与栈顶元素进行比较。
4. 如果相同,则继续比较下一个字符,直到字符串全部比较完毕。
5. 如果不同,则表示该字符串不是对称串,直接返回结果。
6. 如果最后栈为空,表示该字符串是对称串,返回结果为是;否则返回结果为否。
下面是用C语言实现的代码:
```c
#include <stdio.h>
#include <string.h>
#define MAXSIZE 100
typedef struct {
char data[MAXSIZE];
int top;
} SqStack;
void InitStack(SqStack *s) {
s->top = -1;
}
void Push(SqStack *s, char e) {
if (s->top == MAXSIZE - 1) {
printf("Stack is full.\n");
return;
}
s->data[++s->top] = e;
}
char Pop(SqStack *s) {
if (s->top == -1) {
printf("Stack is empty.\n");
return '\0';
}
return s->data[s->top--];
}
int StackEmpty(SqStack *s) {
if (s->top == -1)
return 1;
else
return 0;
}
int Symmetric(char *str) {
SqStack s;
InitStack(&s);
int len = strlen(str);
int i;
for (i = 0; i < len/2; i++) {
Push(&s, str[i]);
}
if (len % 2 != 0) {
i++;
}
while (i < len) {
char temp = Pop(&s);
if (temp != str[i]) {
return 0;
}
i++;
}
if (StackEmpty(&s)) {
return 1;
} else {
return 0;
}
}
int main() {
char str[MAXSIZE];
printf("Please input a string: ");
scanf("%s", str);
if (Symmetric(str)) {
printf("The string is symmetric.\n");
} else {
printf("The string is not symmetric.\n");
}
return 0;
}
```
您可以尝试输入一些字符串进行测试,如:123321、abccba、12321等。
2.设单链表中存放n个字符,试设计一个C语言程序,判断该字符串是否中心对称。
可以通过以下步骤来判断一个单链表中存放的字符串是否中心对称:
1. 遍历单链表,将每个字符存储到一个字符数组中。
2. 计算字符数组的长度n。
3. 从字符数组的两端开始,依次比较对应位置的字符是否相等,直到中间位置。如果每个位置的字符都相等,则说明该字符串是中心对称的。
下面是一个示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char data;
struct node *next;
} Node;
int is_symmetric(Node *head) {
char str[100];
int len = 0;
Node *p = head;
while (p != NULL) {
str[len++] = p->data;
p = p->next;
}
for (int i = 0; i < len / 2; i++) {
if (str[i] != str[len - i - 1]) {
return 0;
}
}
return 1;
}
int main() {
Node *head = NULL;
Node *p = NULL;
char str[] = "abcba";
for (int i = 0; i < sizeof(str) - 1; i++) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = str[i];
node->next = NULL;
if (head == NULL) {
head = node;
p = node;
} else {
p->next = node;
p = node;
}
}
if (is_symmetric(head)) {
printf("The string is symmetric.\n");
} else {
printf("The string is not symmetric.\n");
}
return 0;
}
```
这个程序采用了一个链表来存储字符串,然后通过遍历链表将其转换为字符数组,最后判断字符数组是否中心对称。注意需要在程序结束时释放链表的内存。