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 字符串库中)。
虽然函数 return *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 回答