Saturday, October 30, 2010

poj_3753_根据关键字进行字符串拷贝.cpp

Problem Links:


poj3753,

Problem:


根据关键字进行字符串拷贝















Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 3494Accepted: 707


Description
把源字符串拷贝到目的字符串,如果指定关键字,则以该关键字结束(不包括关键字本身),如果拷贝失败,则得到空串。
具体要求:实现如下函数原型SafeStrcpy2KeyWord(),并在代码中调用该函数实现上述功能。该函数的实现要考虑各种可能的参数取值,以确保程序不出现崩溃。


int SafeStrcpy2KeyWord(char* pDestBuffer, //拷贝的目的地地址

char* pSourceString, //拷贝的源地址

int nDestBufferSize, //拷贝的目的地缓冲区长度

char* szKeyWord); //指定关键字符串

返回值:所拷贝的字符串长度。如果拷贝失败,则返回0。

Input
输入包含多组数据,以EOF结束
每组数据第一行为不含空格的源字符串,长度小于256;接下来的一行或多行都是关键字串(长度小于16),一直到END结束。“NULL”表示关键字串为空,此时输出的拷贝后的长度应为0,拷贝后的字符串为空串(也用”NULL”表示,见下文)。

Output
对于每组数据输出拷贝的长度和拷贝后的目的字符串,以空格分隔。如果该目的字符串为空,则用”NULL”表示。

Sample Input
/home/tony/work_server/1/rtest/relayer.out
/
/t
/1/r
.
NULL
END

Sample Output
0 NULL
5 /home
22 /home/tony/work_server
38 /home/tony/work_server/1/rtest/relayer
0 NULL

Source

Solution:


Do whatever the problem told you to do, but take care:
1st, if there is no match with the keyword, return the whole string.
2nd, take care of the for loop. It takes me 3 or 4 WAs.

Source Code:


[sourcecode language="cpp" collapse="true" padlinenumbers="true"]
//Fri May 28 12:55:30 CDT 2010
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

int SafeStrcpy2KeyWord(string &des, string src, string keyword)
{
if (keyword == "NULL")
{
des.clear();
return 0;
}
int N = keyword.size();
int M = src.size();
for (int i = 0; i + N <= M; i++)
{
string str = src.substr(i, N);
if (str == keyword)
{
return i;
}
des += src[i];
}
return 0;
}

int main(int argc, const char* argv[])
{
// freopen("input.in", "r", stdin);
// freopen("output.out", "w", stdout);
string str;
while (cin >> str)
{
string s;
getchar();
while (getline(cin, s) && s != "END")
{
string des;
int len = SafeStrcpy2KeyWord(des, str, s);
if (len == 0 && des.size() == 0)
cout << "0 NULL" << endl;
else if (len == 0)
cout << str.size() << " " << str << endl;
else
cout << len << " " << str.substr(0, len) << endl;
}
}
// fclose(stdin);
// fclose(stdout);
return 0;
}
[/sourcecode]

No comments :