现在的位置: 首页 > 综合 > 正文

百度之星程序设计大赛-初赛题3-字符串替换

2012年05月06日 ⁄ 综合 ⁄ 共 1898字 ⁄ 字号 评论关闭

第三题(共四题100分):字符串替换(30分)

题目描述:请编写程序,根据指定的对应关系,把一个文本中的字符串替换成另外的字符串。

输入数据:程序读入已被命名为text.txt和dict.txt的两个输入数据文本文件,text.txt为一个包含大量字符串(含中文)的文本,以whitespace为分隔符;dict.txt为表示字符串(s1)与字符串(s2)的对应关系的另一个文本(含中文),大约在1万行左右,每行两个字符串(即s1和s2),用一个\t或空格分隔。dict.txt中各行的s1没有排序,并有可能有重复,这时以最后出现的那次s1所对应的s2为准。text.txt和dict.txt中的每个字符串都可能包含除whitespace之外的任何字符。text.txt中的字符串必须和dict.txt中的某s1完全匹配才能被替换。(为便于调试,您可下载测试text.txt和dict.txt文件,实际运行时我们会使用不同内容的输入文件。)

输出数据:在标准输出上打印text.txt被dict.txt替换后了的整个文本。

评分标准:程序输出结果必须正确,内存使用越少越好,程序的执行时间越快越好。

我的程序:

#pragma warning(disable:4786)
#include 
<string>
#include 
<map>
#include 
<fstream>
#include 
<cassert>
#include 
<cstdio>

using namespace std;

map
< stringstring > dict;

void loadDict(const char *filename)
{
    
string a, b;
    ifstream dic;
    assert(filename 
!= NULL);
    dic.open(filename);
    
while(dic>>a>>b)
    
{
        dict[a] 
= b;
    }

    dic.close();
}


const char *replaceWord(const string &word)
{
    map
< stringstring >::iterator word2 = dict.find(word);
    
if (word2 == dict.end())
    
{
        
return word.c_str();
    }

    
else
    
{
        
return word2->second.c_str();
    }

}


int main()
{
    
bool isChinese = false;
    
char c;
    
string word;
    loadDict(
"dict.txt");
    
    FILE 
*fp = fopen("text.txt""rt");
    
while(!feof(fp))
    
{
        c 
= fgetc(fp);
        
if (isChinese)
        
{
            word 
+= c;
            isChinese 
= false;
        }

        
else
        
{
            
if ((c & 0x80) == 0 && isspace(c))
            
{
                
if (!word.empty())
                
{
                    printf(
"%s", replaceWord(word));
                    word 
= "";
                }

                printf(
"%c", c);
            }

            
else
            
{
                
if (c & 0x80)
                
{
                    isChinese 
= true;
                }

                word 
+= c;
            }

        }

    }

    fclose(fp);

    
if (!word.empty())
    
{
        printf(
"%s", replaceWord(word));
    }

    
return 0;
}

抱歉!评论已关闭.