每天学习一点编程(3)(输出给定字串的全部连续子串)

本文展示了三种不同的C++方法来输出给定字符串的所有连续子串。第一种利用了标准库string,第二种和第三种则不依赖该库,通过字符数组实现。示例代码详细解释了每种方法的实现逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输出给定字串的全部连续子串。
   比如对给给定字符串 “abcd",应该打印出:a,b,c,d,ab,bc,cd,abc,bcd,abcd等。
/*输出给定字串的全部连续子串。
  比如对给给定字符串 “abcd",应该打印出:a,b,c,d,ab,bc,cd,abc,bcd,abcd等。*/

/*方法1:使用标准库 string*/
#include <iostream>
#include <string>
using namespace std;

void print(string s)
{
	if(s.empty())
		return;
	string temp;
	for(string ::size_type index = 0; index != s.size(); ++ index)
	{
		temp = "";
		for(string :: size_type index1 = index; index1 != s.size(); ++ index1)
		{
			temp += s[index1];
		    cout << temp << endl;
		}
	}
}

int main()
{
	string s;
	cout << "please input the string:" << endl;
	getline(cin, s);
	cout << "the print string is:" << endl;
	print(s);
	system("pause");
	return 0;
}

/*方法2:不使用标准库 string*/
#include <iostream>
//#include <string>
#define N 21
using namespace std;


void print(char *s)
{
	if(!s)
		return;
	int len = strlen(s);
	for(int index = 0; index < len; ++ index)
	{
		char temp[N] = "";
		for(int index1 = index; index1 < len; ++ index1)
		{
			temp[index1 - index] = s[index1];
			temp[index1 - index +1] = '\0';
			cout << temp << endl;
		}
	}
}

int main()
{
	char s[N];
	cout << "please input the string:" << endl;
	cin.getline(s, N, '\n');
	cout << "the print string is:" << endl;
	print(s);
	system("pause");
	return 0;
}

/*方法3:不使用标准库 string*/
#include <iostream>
#define N 21
using namespace std;


void print(char *s)
{
	if(!s)
		return;
	int len = strlen(s);
	for(int index = 0; index < len; ++ index)
		for(int index1 = index; index1 < len; ++ index1)
		{
			for(int index2 = index; index2 <= index1; ++index2)
			    cout << s[index2];
			cout << " " << endl;
		}
}

int main()
{
	char s[N];
	cout << "please input the string:" << endl;
	cin.getline(s, N, '\n');
	cout << "the print string is:" << endl;
	print(s);
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值