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

字符串处理

时间:2015-04-21 22:48:40      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

处理一个字符串,把字符串中的‘_‘替换成‘%A2‘,该字符串大空间足够大。要求不开辟新的内存。

比如str[23]="abc_de__h"

处理后:"abc%A2de%A2%A2h"

思路:先把字符串的长度求出来为len.再把‘_‘个数num求出来,新的数字占用内存为len+num*2.接下来就能够进行替换了。

代码如下:


#include <iostream>

#include <string>
using namespace std;


void rep(char *p){

int len = strlen(p);
int num=0,newLen,pos,end;
cout<<len;
//get the number of ‘_‘
//"abc_de__h";
for(int i=0; i<9; i++){
if (p[i] == ‘_‘){
num++;
}
}


//move *pos to the new end
newLen = strlen(p)+2*num;   //new memory
pos = len ;
end = newLen ;



//Move number from end to begin 
while(pos != end)
{


if ( p[pos] != ‘_‘)
{
p[end--] = p[pos--];

}
else{   //if *p == ‘_‘   replace %A2 to ‘_‘

p[end--] = ‘2‘;
p[end--] = ‘A‘;
p[end--] = ‘%‘;
pos --;
}
}

}


int main(){
char strs[256] = "abc_de__h";
rep(strs);
cout<<"newstr:"<<strs;
return 0;
}

字符串处理

标签:

原文地址:http://blog.csdn.net/stefan1240/article/details/45175057

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