您的位置:首页 > 编程语言 > C语言/C++

360笔试题——处理字符串

2015-10-04 16:12 429 查看
题目要求:

先输入要处理的字符串个数n,然后输入n个字符串,经过处理输出字符串。

处理过程:'#','@'为控制符,不应出现在字符中。如果遇到'#',再删除前一个字符和'#',如果遇到'@',则应删除'@'前面所有的字符和'@'。

e.g.

输入:

2

abcc#de

kj@abcde

输出:

abcde

abcde

方式1:低级的方法,用链表

#include <iostream>
#include <string>
using namespace std;
struct node
{
char data;
struct node *next;
};// 注:这里仅仅是声名,可以在后面进行定义。
struct node* creat(string str)
{
struct node *head, *p1, *p2;
head = p1 = p2 = (struct node *)malloc(sizeof(struct node));
string::size_type i = 0;
while (str[i] == '@' || str[i] == '#' || str[i+1] == '@' || str[i+1] == '#')
i++;
p1->data = str[i];
i++;
for (; i < str.size(); i++)
{
p2->next = p1;
p2 = p1;
p1 = (struct node *)malloc(sizeof(struct node));
while (i + 1 < str.size() && (str[i] == '#' || str[i] == '@' || str[i + 1] == '#' || str[i + 1] == '@'))
{
if (str[i + 1] == '@' || str[i + 1] == '#')
{
if (str[i + 1] == '@')
{
head = p2 = p1;
}
i += 2;
}
else
{
if (str[i] == '@')
head = p2 = p1;
else;
i++;
}
}
if (i < str.size() )
p1->data = str[i];
}
p2->next = p1;
p1->next = nullptr;
return head;
}
void print(node *head)
{
node *p;
p = head;
if (nullptr != head)
{
while (nullptr != p)
{
cout << p->data;
p = p->next;
}
cout << endl;
}
else
cout << "链表无效!" << endl;
}
void main()
{
string a[100] = {""};
int cnt;
cin >> cnt;
for (int i = 0; i < cnt; i++)
{
cin >> a[i];
}
cout << "原链表:" << endl;
for (int i = 0; i < cnt; i++)
{
cout << a[i] << endl;
}

//struct node *head;
struct node *b[100];
for (int i = 0; i < cnt; i++)
{
b[i] = creat(a[i]);
}

cout << "校验后:" << endl;
for (int i = 0; i < cnt; i++)
{
print(b[i]);
}
}


方式2:用容器vector,string,迭代器iterator;

#include <vector>
#include <iostream>
#include <string>
using namespace std;
void main()
{
vector<string> str;
int cnt;
string t;
cin >> cnt;
for (int i = 0; i < cnt; i++)
{
cin >> t;
str.push_back(t);
}
vector<string>::iterator it_vec;
string::iterator it_str;
for (it_vec = str.begin(); it_vec != str.end(); ++it_vec)
{
for (it_str = (*it_vec).begin(); it_str != (*it_vec).end();)
{
if (*it_str == '#')
{
if (it_str == (*it_vec).begin())
(*it_vec).erase(it_str);
else
{
(*it_vec).erase(it_str - 1);
it_str--;
(*it_vec).erase(it_str);
it_str--;
++it_str;
}
}
else if (*it_str == '@')
{
it_str = (*it_vec).erase((*it_vec).begin(), it_str + 1);
}
else
++it_str;
}
}
for (it_vec = str.begin(); it_vec != str.end(); ++it_vec)
{
cout << *it_vec << endl;
}
}

方式3:精简的方法

#include <iostream>
#include <string>
using namespace std;
void main()
{
string str;
cin >> str;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == '#')
{
if (i != 0)
str[i - 1] = '#';
}
if (str[i] == '@')
{
for (int j = 0; j <= i; j++)
str[j] = '@';
}
}
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] != '#' && str[i] != '@')
cout << str[i];
}
cout << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息