码迷,mamicode.com
首页 > 其他好文 > 详细

【hihoCoder】1082: 然而沼跃鱼早就看穿了一切

时间:2016-09-24 23:29:34      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:

  题目:http://hihocoder.com/problemset/problem/1082

输入一个字符串,将其中特定的单词替换成另一个单词

  代码注意点:

1. getline(istream &in, string &s)

  • 没有读入字符,将返回false

2. transform(tmp.begin(),tmp.end(),tmp.begin(),::tolower)

  • 将tmp的所有字母都改成小写
  • 需要包含 #include <algorithm>

3. 查找函数:size_t find(const string& str, size_t pos = 0) const

  • 用法:string s, t; s.find(t, 0); 从s的0位置开始查找t是不是出现在s中
  • 返回出现t在s中出现的位置。如果没有找到,则返回 string::npos

4. 替换函数:string& replace(size_type pos(开始替换的位置),size_type cnt(替换的个数), const basic_string str(用来替换的字符串))

  • 用法:string s, t; s.replace(0, 3, t); 从pos开始删除cnt个字母,然后在pos位置插入str
  • 返回替换后的字符串

  源码  

技术分享
 1 #include <iostream>
 2 #include<string>
 3 #include <vector>
 4 #include <algorithm>  
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     string str;
10     string temp;;
11     string target="marshtomp";
12     string Des="fjxmlhx";
13     string ::size_type tLength=target.length();
14     string ::size_type dLength=Des.length();
15     vector<string> output;
16     //getline(cin,str);
17     while (getline(cin,str) )
18     {
19         temp=str;
20         //转换成小写    
21                 transform(temp.begin(),temp.end(),temp.begin(),::tolower);
22         string ::size_type pos=0;
23         //可能有多处匹配成功的位置!!!
24         while ( (pos=temp.find(target,pos))<str.length())
25         {
26             str.replace(pos,tLength,Des);
27             temp.replace(pos,tLength,Des);
28             pos+=dLength;
29         }
30         output.push_back(str);            
31     }
32     for (vector<string>::size_type i=0;i<output.size();i++)
33         cout<<output[i]<<endl;
34     return 0;
35 }
View Code

【hihoCoder】1082: 然而沼跃鱼早就看穿了一切

标签:

原文地址:http://www.cnblogs.com/coolqiyu/p/5904296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!