开发者

How to modify char array

I am reading a char array newpath that contains C:\\Program Files\\test software\\app . How to substitute the space to underscore character?

char newPath2[MAX_PATH];
int newCount2 = 0;

for(int i=0; i < strlen(newPath); i++)
 {
 if(newPath[i] == ' ')
    {
     newPath2[i] = '_';         
    }
    newPath2[newCount2开发者_Go百科]=0;
 }


newCount2 is always 0, I think you need to increment this counter too. If not Im not sure what you are doing with this statement newPath2[newCount2]=0;

I think you want this:

for(int i=0; i < strlen(newPath); i++)
 {
 if(newPath[i] == ' ')
    {
     newPath2[i] = '_';         
    }else{
     newPath2[i]=newPath[i];
    }
 }


Don't use strlen in for, is uses O(n) time - loops through the entire string each time it's called - so will make your for run very slowly as it gets called each step in the for.

Better:

char newPath2[MAX_PATH];
int newCount2 = 0;
const int length = strlen(newPath);

for(int i=0; i < length; i++)
 {
   if(newPath[i] == ' ')
    {
     newPath2[newCount2++] = '_';         
    } else {
     newPath2[newCount2++] = newPath[i];
    }
 }

This way if you need to replace space with, say, two characters (like \<space>), you could easily replace newPath2[newCount2++] = '_' with: newPath2[newCount2++] = '\\'; newPath2[newCount2++] = ' ';

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜