由字符串替换程设,发现string的find及replace使用陷阱
另外今天通过设置,可以避免每次update到github输入用户名密码的问题了,感谢Zippera大神: )
http://zipperary.com/2013/05/26/ssh-errors-with-github/
这是一道程设初级的题目,但是发现还是会遇到问题,字符串替换,我使用cpp string比较安全,find repalce函数
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <iomanip>
#include <sstream>
#define Min(a,b) (((a) < (b)) ? (a) : (b))
#define Max(a,b) (((a) > (b)) ? (a) : (b))
#define read freopen("in.txt","r",stdin)
#define write freopen("out.txt","w",stdout)
using namespace std;
int main()
{
read;
write;
string str,oristr,newstr,sentence;
vector<string> orivec;
vector<string> newvec;
while(getline(cin,str))
{
if(str.size()==0) break;//finish rule
istringstream istr(str);
getline(istr,oristr,'|');
getline(istr,newstr,'|');
orivec.push_back(oristr);
newvec.push_back(newstr);
}
int startindex;
while(getline(cin,sentence))
{
if(sentence.size()==0) continue;
for(int i=0;i<orivec.size();i++)
{
while((startindex=sentence.find(orivec.at(i),0))!=-1)
{
sentence.replace(startindex,orivec.at(i).size(),newvec.at(i));
}
}
break;
}
cout<<sentence<<endl;
return 0;
}
问题1:find函数本来找不到是返回string::npos, 用这样一个静态变量表示找不到,类似于迭代器的end(),实际该位置是不存在合法字符的,但是VS确返回了-1,此时npos返回 2^32-1, 不知为何
经过July群里的大神解答,问题1解决,npos是 size_t 类型,32bit下是unsigned int, 是因为一个无符号数 32个1(无符号表示2^32-1) 赋给了一个有符号数(32个全1被认为是-1),所以 unsigned int 和 int比较的时候 都会转化为 int 然后其实 还是相等的,
或许npos是为了便于跨平台,因为到了64bit平台, 64全1,赋给符号整数也是作为补码,也是变为-1
问题2:replace函数一直担心如果替换后的字符串比源串长,如何不覆盖后面的字符,如果短,是否会自动拼接。回答,是的,会的,之前以为不会是因为用法不多,replace(start,length,string)中的length实际是原子串的长度,
而我以为是替换后的长度,怪不得用不对,以后可以避免了,还可以用迭代器替换index,尽管我不喜欢= = 另外发现cplusplus有个 cpp.sh 可以自动网页执行代码,威武啊!