6-1 判断回文字符串 分数 20 作者 C课程组 单位 浙江大学 本题要求编写函数,判断给定的一串字符是否为“回文”。所谓“回文”是指顺读和倒读都一样的字符串。如“XYZYX”和“xyzzyx”都是回文。 函数接口定义: bool palindrome( char *s ); 函数palindrome判断输入字符串char *s是否为回文。若是则返回true,否则返回false。 裁判测试程序样例: #include <stdio.h> #include <string.h> #define MAXN 20 typedef enum {false, true} bool; bool palindrome( char *s ); int main() { char s[MAXN]; scanf("%s", s); if ( palindrome(s)==true ) printf("Yes\n"); else printf("No\n"); printf("%s\n", s); return 0; } /* 你的代码将被嵌在这里 */ 输入样例1: thisistrueurtsisiht 输出样例1: Yes thisistrueurtsisiht 输入样例2: thisisnottrue 输出样例2: No thisisnottrue
时间: 2023-12-03 07:42:00 浏览: 185
```c
bool palindrome(char *s) {
int len = strlen(s);
for (int i = 0; i < len / 2; i++) {
if (s[i] != s[len - i - 1]) {
return false;
}
}
return true;
}
```
相关问题
6-10 指定位置输出字符串 分数 10 作者 C课程组 单位 浙江大学 本题要求实现一个函数,对给定的一个字符串和两个字符,打印出给定字符串中从与第一个字符匹配的位置开始到与第二个字符匹配的位置之间的所有字符。
以下是实现该功能的C语言代码:
```c
#include <stdio.h>
void printStrBetweenChars(char* str, char c1, char c2) {
int i, startIndex, endIndex;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == c1) {
startIndex = i;
}
if (str[i] == c2) {
endIndex = i;
break;
}
}
for (i = startIndex+1; i < endIndex; i++) {
printf("%c", str[i]);
}
}
int main() {
char str[] = "Hello, World!";
char c1 = 'o';
char c2 = 'd';
printStrBetweenChars(str, c1, c2); // 输出 "llo, W"
return 0;
}
```
在上面的代码中,我们首先遍历给定字符串,找到第一个匹配的字符位置和第二个匹配的字符位置,然后从第一个字符位置的下一个字符开始,到第二个字符位置之间的所有字符都被输出。
python编写一个函数,给定一个字符串,判断该字符串是否为回文
一个回文字符串是指正着读和倒着读都是一样的字符串,比如 "racecar"。可以使用以下代码实现:
```python
def is_palindrome(string):
# 判断字符串是否为回文
return string == string[::-1]
```
这里使用了 Python 中的字符串切片语法,`string[::-1]` 表示将字符串反转。如果反转后的字符串和原字符串相同,那么就是回文字符串,返回 `True`;否则返回 `False`。
相关推荐
![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_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)