输入一个字符串,统计指定字符的个数。例如:字符串\"abcddcba\",指定字符'c',则统计个数为2。
时间: 2023-04-30 12:00:34 浏览: 36
可以使用循环遍历字符串中的每一个字符,判断是否与指定字符相同,如果相同则计数器加1。最后返回计数器的值即可。
示例代码如下:
```
def count_char(s, c):
count = 0
for i in s:
if i == c:
count += 1
return count
s = "abcddcba"
c = "c"
print(count_char(s, c)) # 输出2
```
相关问题
从键盘输入一个字符串,判断是否形成回文,即正序和逆序一样,如abcddcba。
可以使用双指针法,从字符串的两端开始向中间扫描,判断对应位置的字符是否相同。如果相同,则继续向中间扫描;如果不同,则说明不是回文字符串。
具体实现可以参考以下代码:
```python
s = input() # 从键盘输入一个字符串
left, right = , len(s) - 1 # 初始化左右指针
while left < right:
if s[left] != s[right]: # 如果对应位置的字符不同
print("不是回文字符串")
break
left += 1 # 左指针向右移动
right -= 1 # 右指针向左移动
else:
print("是回文字符串")
```
注意,这里使用了 `else` 语句,它会在循环正常结束(即没有被 `break` 中断)时执行,因此可以在循环结束后判断是否是回文字符串。
设单链表中存放着n个字符,试判断字符串是否是中心对称,如abcddcba即为中心对称的字符串。用C语言做个程序
好的,可以按照以下步骤实现:
1. 定义链表节点结构体,包括字符数据和指向下一个节点的指针。
2. 输入n个字符,创建一个单链表。
3. 定义两个指针,分别从链表头和链表尾开始向中间遍历,判断对应字符是否相等。
4. 如果一直相等,则是中心对称的字符串;否则不是。
下面是完整的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct node {
char data;
struct node *next;
} Node;
int main() {
int n, i;
char ch;
Node *head = NULL, *tail = NULL, *p, *q;
printf("请输入n:");
scanf("%d", &n);
// 输入n个字符,创建链表
printf("请输入%d个字符:", n);
for (i = 0; i < n; i++) {
scanf(" %c", &ch);
// 创建新节点
p = (Node*) malloc(sizeof(Node));
p->data = ch;
p->next = NULL;
// 将新节点插入链表尾部
if (head == NULL) {
head = p;
} else {
tail->next = p;
}
tail = p;
}
// 判断字符串是否是中心对称的
p = head;
q = tail;
while (p != q && p->next != q) {
if (p->data != q->data) {
printf("该字符串不是中心对称的字符串!\n");
return 0;
}
p = p->next;
q = q->next;
}
printf("该字符串是中心对称的字符串!\n");
// 释放链表空间
p = head;
while (p != NULL) {
q = p->next;
free(p);
p = q;
}
return 0;
}
```
在输入n和n个字符后,程序会遍历链表判断字符串是否中心对称。如果是中心对称的,程序会输出"该字符串是中心对称的字符串!";否则程序会输出"该字符串不是中心对称的字符串!"。最后,为了避免内存泄漏,需要释放链表空间。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.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)