输入:fdfsdf%abd$cdef
输出:abcdef
1、C不完全实现法
#include <conio.h>
#include <stdio.h>
#include <string.h>
void func(char *des, char *str, unsigned int len)
{
//printf("%s\n", str);
char *p = des;
while (len)
{
if (*str == '$')
{
if (des > p)
{
des--;
}
}
else if (*str == '%')
{
des = p;
}
else
{
*des= *str;
des++;
}
str++;
len--;
}
*des = '\0';
}
int main()
{
char str[1024];
char des[1024] = { 0 };
while (1)
{
printf("please enter string:\n");
scanf_s("%s", str, 1024);
//printf("%d\n", strlen(str));
func(des, str, strlen(str));
if (strlen(des) != 0)
printf("%s\n", des);
else
printf("it is empty!\n");
}
_getch();
return 0;
}
2、C++实现法
#include <conio.h>
#include <iostream>
#include <string>
#include <iterator>
using namespace std;
int main()
{
string str;
string::iterator it;
while (getline(cin, str))
{
it = str.begin();
while (1)
{
if (*it == '$')
{
if (it != str.begin())
{
it--;
it = str.erase(it);
}
it = str.erase(it);
}
else if (*it == '%')
{
it = str.erase(str.begin(), it);
it = str.erase(it);
}
else
it++;
if (it == str.end())
{
break;
}
}
if (!str.empty())
cout << str << endl;
else
cout << "str is temp!" << endl;
}
_getch();
return 0;
}