char testStr[] = " trim this ";
char** pTestStr = &testStr;
trim(pTestStr);
int trim(char** pStr)
{
char* str = *pStr;
while(isspace(*str)) {
(*pStr)++;
str++;
}
if(*str == 0) {
return 0;
}
char *end = str + strlen(str) - 1;
while(end > str && isspace(*end))
end--;
*(end+1) = 0;
return 0;
}
8009 次
3 に答える
5
testStr
書き込み可能にする必要があります:
char testStr[] = " trim this ";
問題は、読み取り専用メモリにある実際のリテラル文字列char *ptr = ...
をptr
指していることです。
を使用char testStr[] = ...
すると、配列が割り当てられ、配列がリテラル文字列と同じ内容で初期化されます。これは配列なので、書き込み可能です。
于 2010-06-11T00:43:31.680 に答える
2
char testStr[] = " trim this ";
char* pTestStr = &testStr[0];
trim(&pTestStr);
void trim(char* str)
{
if(!str)
return;
char* ptr = str;
int len = strlen(ptr);
while(len-1 > 0 && isspace(ptr[len-1]))
ptr[--len] = 0;
while(*ptr && isspace(*ptr))
++ptr, --len;
memmove(str, ptr, len + 1);
}
于 2010-06-17T19:28:06.560 に答える
0
編集: zStringライブラリの最新バージョンに基づいてコードを更新しました。
以下は、trim
、left-trim
および 、right-trim
関数の実装です ( zString 文字列ライブラリに追加されます)。
関数は を返し*char
ますが、元の文字列が変更されているため、これらは目的に役立ちます。
などの標準ライブラリ関数を使用できますisspace()
が、以下の実装は必要最小限のコードであり、ライブラリ関数に依存していません。
/* trim */
char *zstring_trim(char *str){
char *src=str; /* save the original pointer */
char *dst=str; /* result */
char c;
int is_space=0;
int in_word=0; /* word boundary logical check */
int index=0; /* index of the last non-space char*/
/* validate input */
if (!str)
return str;
while ((c=*src)){
is_space=0;
if (c=='\t' || c=='\v' || c=='\f' || c=='\n' || c=='\r' || c==' ')
is_space=1;
if(is_space == 0){
/* Found a word */
in_word = 1;
*dst++ = *src++; /* make the assignment first
* then increment
*/
} else if (is_space==1 && in_word==0) {
/* Already going through a series of white-spaces */
in_word=0;
++src;
} else if (is_space==1 && in_word==1) {
/* End of a word, dont mind copy white spaces here */
in_word=0;
*dst++ = *src++;
index = (dst-str)-1; /* location of the last char */
}
}
/* terminate the string */
*(str+index)='\0';
return str;
}
/* right trim */
char *zstring_rtrim(char *str){
char *src=str; /* save the original pointer */
char *dst=str; /* result */
char c;
int is_space=0;
int index=0; /* index of the last non-space char */
/* validate input */
if (!str)
return str;
/* copy the string */
while(*src){
*dst++ = *src++;
c = *src;
if (c=='\t' || c=='\v' || c=='\f' || c=='\n' || c=='\r' || c==' ')
is_space=1;
else
is_space=0;
if (is_space==0 && *src)
index = (src-str)+1;
}
/* terminate the string */
*(str+index)='\0';
return str;
}
/* left trim */
char *zstring_ltrim(char *str){
char *src=str; /* save the original pointer */
char *dst=str; /* result */
char c;
int index=0; /* index of the first non-space char */
/* validate input */
if (!str)
return str;
/* skip leading white-spaces */
while((c=*src)){
if (c=='\t' || c=='\v' || c=='\f' || c=='\n' || c=='\r' || c==' '){
++src;
++index;
} else
break;
}
/* copy rest of the string */
while(*src)
*dst++ = *src++;
/* terminate the string */
*(src-index)='\0';
return str;
}
于 2016-02-24T21:05:51.207 に答える