C++程序中查找以给定字符串开头和结尾的不同子字符串
在本教程中,我们将编写一个程序,查找以给定字符串开头和结尾的子字符串的总数。
给定一个字符串和两个子字符串。我们需要找到以给定的两个子字符串开头和结尾的不同子字符串的数量。让我们来看一个例子。
输入
str = "getmesomecoffee" start = "m" end = "e"
输出
6
给定字符串中共有6个不同的子字符串。它们是 **me, mesome, mesomemecoffe, mesomemecoffee, mecoffe, mecoffee。**
让我们看看解决问题的步骤。
初始化字符串。
遍历字符串并找到开头和结尾子字符串的索引。将它们存储在单独的数组中。
初始化一个集合来存储不同的子字符串。
遍历字符串。
检查当前索引是否与我们之前形成的数组的起始字符串匹配。
如果我们找到起始字符串的索引,则搜索结束字符串。
将所有字符串添加到一个变量中,直到我们找到结尾。
当我们找到结束字符串时,递增子字符串计数并将子字符串添加到集合中。
重置子字符串变量。
打印子字符串计数。
示例
让我们看看代码。
#include <bits/stdc++.h>
using namespace std;
int getSubstringsCount(string str, string start, string end) {
int substrings_count = 0, str_length = str.size(), start_length = start.size(), end_length = end.size();
int start_matches_index[str_length] = {0}, end_matches_index[str_length] = {0};
for (int i = 0; i < str_length; i++) {
if (str.substr(i, start_length) == start) {
start_matches_index[i] = 1;
}
if (str.substr(i, end_length) == end) {
end_matches_index[i] = 1;
}
}
set<string> substrings;
string current_substring = "";
for (int i = 0; i < str_length; i++) {
if (start_matches_index[i]) {
for (int j = i; j < str_length; j++) {
if (!end_matches_index[j]) {
current_substring += str[j];
}
if (end_matches_index[j]) {
current_substring += str.substr(j, end_length);
if (substrings.find(current_substring) == substrings.end()) {
substrings_count++;
}
substrings.insert(current_substring);
}
}
current_substring = "";
}
}
return substrings_count;
}
int main() {
string str = "getmesomecoffee";
string start = "m";
string end = "e";
cout << getSubstringsCount(str, start, end) << endl;
return 0;
}输出
如果执行上述程序,则会得到以下结果。
6
结论
如果您在本教程中有任何疑问,请在评论部分提出。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP