三种方式实现——生成字符串的所有子串

#include<iostream>
#include<string>
#include<ctime>
std::string mySubstr(const std::string& , const int& , const int& );
int main()
{
	std::ios::sync_with_stdio(false);
	std::cin.tie(0);
	std::string str;  // 待输入的字符串;
	while (std::cin >> str) {
		
		for (int index = 0; index < str.length(); ++index) {
			for (int subStrLen = str.length() - index; subStrLen > 0; --subStrLen) {
				// std::cout << str.substr(index, subStrLen) << std::endl; // 第一种方式;
				std::cout << mySubstr(str, index, subStrLen) << std::endl; // 第二种方式;
			}
		}
	}
	return 0;
}
std::string mySubstr(const std::string& str, const int& index, const int& len) {
	//return std::string(str, index, len);  // 方式二:通过匿名对象实现;
	std::string temp;
	for (int i = index; i < index + len; ++i) {
		temp += str[i];  // 注意: 此表达式与 temp = str[i] + temp; 会生成相反顺序的字符串对;
	}
	return temp;
}

说明:

如需要进行存储,可以借助 vector 快速实现动态数组。
可以参考两年前笔者写的一篇博客:
有关字符串的分割、生成所有子串、字符串全排列组合
不过较之于 vector,推荐多多使用 set,参考指着另外一篇文章:
由一道公共子串题目引起的自我反思

后记:

转载请注明出处。
2019/11/23 00:10
[email protected]

发布了89 篇原创文章 · 获赞 159 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/I_love_you_dandan/article/details/103209201