写一个查找HI!XIDIAN中I的个数的C语言程序
时间: 2023-03-08 18:59:16 浏览: 43
int count = 0;
for (int i = 0; i < strlen(hixidian); i++)
{
if (hixidian[i] == 'I')
count++;
}
printf("在HI!XIDIAN中I的个数为%d\n", count);
相关问题
写一个查找HI!XIDIAN中I的C语言程序
### 回答1:
你可以使用以下C语言程序来查找HI!XIDIAN中的I: ```
#include <stdio.h>
int main()
{
char str[] = "HI!XIDIAN";
int i;
for (i=0; str[i] != '\0'; i++)
{
if (str[i] == 'I')
{
printf("找到 'I' 在位置 %d\n", i);
}
}
return 0;
}
```
### 回答2:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "HI!XIDIAN";
char ch = 'I';
int flag = 0;
for (int i = 0; i < strlen(str); i++) {
if (str[i] == ch) {
printf("%c is found at index %d\n", ch, i);
flag = 1;
}
}
if (!flag) {
printf("%c is not found in the string\n", ch);
}
return 0;
}
这段程序可以实现在给定字符串"HI!XIDIAN"中查找字符'I'的功能。首先,我们定义一个字符串数组str,存储待查找的字符串;同时,定义一个字符变量ch,存储要查找的字符。然后,设定一个标志变量flag,初始化为0。
通过使用for循环遍历字符串str,逐个检查字符串中的字符是否与目标字符ch相等。如果发现相等的字符,就打印出该字符及其所在的索引位置,并将标志变量flag设置为1。如果整个字符串都被遍历完毕,但没有找到目标字符,那么标志变量flag的值不会改变,此时输出"目标字符在字符串中未找到"的提示信息。
该程序的运行结果为:"I is found at index 2"。
判断一个字符串在另一个字符串
中出现的次数,该怎么做?
您好,根据您的要求,您可以使用 Python 中的 count 方法来统计一个字符串在另一个字符串中出现的次数。该方法会返回指定字符串在目标字符串中出现的次数。以下是使用 count 方法的示例代码:
```python
str1 = "hello world"
str2 = "l"
count = str1.count(str2)
print(count) # 输出结果为 3
```
在上述示例中,我们统计了字符串 "l" 在字符串 "hello world" 中出现的次数,得到的结果为 3。希望这个回答可以帮助到您。