2011-03-02 20 views
0

我正在閱讀包含C:\\Program Files\\test software\\app的字符數組newpath。如何替換空格來突出字符?如何修改字符數組

char newPath2[MAX_PATH]; 
int newCount2 = 0; 

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

回答

1

newCount2總是0,我想你也需要增加這個計數器。如果沒有您的IM與此聲明newPath2[newCount2]=0;

做不知道我想你想的:

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

不要在for使用strlen,是使用O(n)的時間 - 在整個循環字符串每次被調用 - 這樣會使得您的for運行得非常緩慢,因爲它被調用for中的每個步驟。

更好:

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]; 
    } 
} 

這樣,如果你需要替換,比方說,兩個字符(如\<space>),你可以很容易地更換newPath2[newCount2++] = '_'與空間:newPath2[newCount2++] = '\\'; newPath2[newCount2++] = ' ';

+1

'const'正確性'長度',請;) – 0xC0000022L 2011-03-02 04:33:23