给你若干字符串,请编程输出没个字符串的子串个数(C++)
时间: 2024-03-16 14:45:27 浏览: 63
C语言求两个字符串的最长公共子串
好的,以下是一个简单的 C++ 代码实现:
```C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string strings[] = {"abc", "defg", "hijkl"};
int n = sizeof(strings) / sizeof(strings[0]);
for (int i = 0; i < n; i++) {
int count = strings[i].length() * (strings[i].length()+1) / 2;
cout << "The string '" << strings[i] << "' has " << count << " substrings." << endl;
}
return 0;
}
```
输出结果为:
```
The string 'abc' has 6 substrings.
The string 'defg' has 10 substrings.
The string 'hijkl' has 15 substrings.
```
该代码利用了一个公式,即一个长度为n的字符串有n*(n+1)/2个子串。通过循环遍历每个字符串,计算它们的子串个数并输出即可。
阅读全文