编写一个程序求一个子串在一个字符串中出现的次数,如果该字符不出现则返回0
时间: 2024-03-07 14:47:39 浏览: 21
好的,以下是 Python 代码实现:
```python
def count_substring(string, sub):
count = 0
for i in range(len(string)):
if string[i:i+len(sub)] == sub:
count += 1
return count
# 示例用法
print(count_substring("hello world", "l")) # 输出 3
print(count_substring("hello world", "lo")) # 输出 1
print(count_substring("hello world", "x")) # 输出 0
```
该函数接受两个字符串参数 `string` 和 `sub`,分别代表字符串和要查找的子串。函数使用一个循环遍历字符串的每个字符,每次判断当前字符和之后的若干个字符是否与子串 `sub` 相等,如果相等则计数器 `count` 加一。最后返回计数器的值。如果子串 `sub` 在字符串 `string` 中不存在,则计数器的初始值为 0,函数直接返回 0。
相关问题
指针2.编写一个程序求一个子串在一个字符串中出现的次数,如果该字符不出现则 返回0。、
以下是一个简单的 C++ 程序,用于求一个子串在一个字符串中出现的次数:
```cpp
#include <iostream>
#include <string>
using namespace std;
int countSubstring(string str, string subStr) {
int count = 0;
size_t pos = 0;
while ((pos = str.find(subStr, pos)) != string::npos) {
++count;
pos += subStr.size();
}
return count;
}
int main() {
string str = "Hello, world! This is a test string.";
string subStr = "is";
int count = countSubstring(str, subStr);
cout << "The substring \"" << subStr << "\" appears " << count << " times in the string." << endl;
return 0;
}
```
在这个程序中,我们定义了一个名为 `countSubstring` 的函数,该函数接受两个参数:一个字符串 `str` 和一个子串 `subStr`。该函数使用 `std::string::find` 函数来查找子串在原始字符串中的位置,并在找到每个子串时将计数器 `count` 增加 1。最后,该函数返回计数器的值,该值表示子串在原始字符串中出现的次数。
在 `main` 函数中,我们定义了一个测试字符串 `str` 和一个子串 `subStr`,并使用 `countSubstring` 函数来计算子串在字符串中出现的次数。最后,我们将结果输出到控制台。
编写一个程序求一个子串在一个字符串中出现的次数,如果该字符不出现则返回0。用c语言编写代码
以下是一个示例代码:
```
#include <stdio.h>
#include <string.h>
int countSubstring(char *string, char *substring) {
int count = 0;
int subLen = strlen(substring);
if (subLen == 0) {
return count;
}
char *pos = string;
while ((pos = strstr(pos, substring)) != NULL) {
count++;
pos += subLen;
}
return count;
}
int main() {
char string[100], substring[100];
printf("Enter a string: ");
fgets(string, 100, stdin);
printf("Enter a substring: ");
fgets(substring, 100, stdin);
int count = countSubstring(string, substring);
printf("The substring '%s' appears %d times in '%s'\n", substring, count, string);
return 0;
}
```
该程序使用 `countSubstring` 函数来计算一个字符串中子串出现的次数。该函数首先计算子串的长度,如果长度为0,则直接返回0。然后使用 `strstr` 函数在字符串中查找子串,每次找到一个子串后就将计数器增加1,并移动查找位置到该子串的下一个位置。最后返回计数器的值。
在 `main` 函数中,程序首先读取用户输入的字符串和子串,然后调用 `countSubstring` 函数来计算子串在字符串中出现的次数,并输出结果。