C编程实现反转字符串,但其指定的子串不反转

给定一个字符串、一个字符串的子串,将第一个字符串反转,但保留子串的顺序不变

例如:

输入:第一个字符串: “Welcome you, my friend”

子串:“you”

输出:“dneirf ym,you emocleW”

解析

(1)扫描一遍第一个字符串,然后用stack把它反转,同时记录下子串的位置。

(2)扫描一遍把记录下来的子串再用stack反转

(3)将堆栈的字符串弹出,这样子串又恢复了原来的顺序#include

#include <cassert>
#include <stack>

using namespace std;

void reverse(const char* s1, const char* token, char* buffer)
{
	stack<char> stack1;
	const char* ptoken = token, *head = s1, *rear = s1;
	assert(s1 && token);

	while (*head != '\0')
	{
		while (*head != '\0' && *ptoken == *head) //是否匹配到不反转的字符的第一个字符
		{
			ptoken++;
			head++;
		}

		if (*ptoken == '\0') //匹配到完整的不反转字符串
		{
			const char* p;
			for (p = head - 1; p >= rear; p--)
			{
				stack1.push(*p);
			}
			ptoken = token;
			rear = head;
		}
		else
		{
			stack1.push(*rear++); //如果没有匹配到则将指针重置
			head = rear;
			ptoken = token;
		}
	}
	
	while (!stack1.empty())
	{
		*buffer++ = stack1.top();
		stack1.pop();
	}
	*buffer = '\0';
}


int main()
{
	char str[100] = "Welcome yoyou, my friend you";

	char token[100] = "you";

	char buffer[100];

	reverse(str,token,buffer);

	cout << buffer << endl;  

	system("pause");
	return 0;
}
发布了55 篇原创文章 · 获赞 1 · 访问量 3796

猜你喜欢

转载自blog.csdn.net/lpl312905509/article/details/104083221
今日推荐