用C语言修剪字符串

用C语言修剪字符串,c,winapi,string,C,Winapi,String,简而言之: < >我使用了Win32和标准C API(在MCSV2008中编译,这样我就可以访问所有C++的东西,但是我只是想修剪一下 char */COD>)。p> 考虑到有strchr,strtok,以及各种其他字符串函数,当然应该有一个trim函数,或者一个可以重新调整用途的函数 谢谢您可以使用ctype.h中的标准函数来实现这一点。只需比较字符数组的开始字符和结束字符,直到两端不再有空格 “空间”包括: ''(0x20)空间(SPC) '\t'(0x09)水平选项卡(选项卡) '\n'(

简而言之:

< >我使用了Win32和标准C API(在MCSV2008中编译,这样我就可以访问所有C++的东西,但是我只是想修剪一下<代码> char */COD>)。p> 考虑到有
strchr
strtok
,以及各种其他字符串函数,当然应该有一个trim函数,或者一个可以重新调整用途的函数

谢谢

您可以使用ctype.h中的标准函数来实现这一点。只需比较字符数组的开始字符和结束字符,直到两端不再有空格

“空间”包括:

''(0x20)空间(SPC)

'\t'(0x09)水平选项卡(选项卡)

'\n'(0x0a)换行符(左前)

'\v'(0x0b)垂直选项卡(VT)

'\f'(0x0c)馈送(FF)

'\r'(0x0d)回车符(CR)

虽然没有任何函数可以为您完成所有工作,但您必须滚动自己的解决方案来重复比较给定字符数组的每一侧,直到没有空格为止

编辑:


既然你已经进入C++,Boost已经等着你让你的生活变得更容易了。

< P>没有标准库函数来完成这项工作,但是你自己也不难。关于这样做有一个问题,源代码对此给出了答案。

最简单的方法是简单的循环。我假设您希望将修剪过的字符串返回原位

char *
strTrim(char * s){
    int ix, jx;
    int len ;
    char * buf 
    len = strlen(s);  /* possibly should use strnlen */
    buf = (char *) malloc(strlen(s)+1);

    for(ix=0, jx=0; ix < len; ix++){
       if(!isspace(s[ix]))
          buf[jx++] = s[ix];

    buf[jx] = '\0';
    strncpy(s, buf, jx);  /* always looks as far as the null, but who cares? */
    free(buf);            /* no good leak goes unpunished */
    return s;             /* modifies s in place *and* returns it for swank */
 }
char*
strTrim(字符*s){
int ix,jx;
内伦;
char*buf
len=strlen;/*可能应使用strnlen*/
buf=(char*)malloc(strlen+1);
对于(ix=0,jx=0;ix

如果String.Trim没有嵌入空格,那么它还需要更多的逻辑。

看到这样的实现很惊讶。我通常这样做:

char *trim(char *s) {
    char *ptr;
    if (!s)
        return NULL;   // handle NULL string
    if (!*s)
        return s;      // handle empty string
    for (ptr = s + strlen(s) - 1; (ptr >= s) && isspace(*ptr); --ptr);
    ptr[1] = '\0';
    return s;
}

它快速可靠-为我服务了很多年。

这让我想写我自己的-我不喜欢提供的功能。在我看来应该有3个功能

char *ltrim(char *s)
{
    while(isspace(*s)) s++;
    return s;
}

char *rtrim(char *s)
{
    char* back = s + strlen(s);
    while(isspace(*--back));
    *(back+1) = '\0';
    return s;
}

char *trim(char *s)
{
    return rtrim(ltrim(s)); 
}
void inPlaceStrTrim(char*str){
int k=0;
int i=0;
对于(i=0;str[i]!='\0';){
if(isspace(str[i])){
//我们有一个空间。。。
k=i;

对于(int j=i;j这如何?…它只需要对字符串进行一次迭代(不使用strlen,它会对字符串进行迭代)。当函数返回时,您会得到一个指向已修剪字符串的开始的指针,该字符串以null结尾。该字符串从左开始修剪空格(直到找到第一个字符)。最后一个非空格字符后的所有尾随空格也将被修剪

char* trim(char* input) {
    char* start = input;
    while (isSpace(*start)) { //trim left
        start++;
    }

    char* ptr = start;
    char* end = start;
    while (*ptr++ != '\0') { //trim right
        if (!isSpace(*ptr)) { //only move end pointer if char isn't a space
            end = ptr;
        }
    }

    *end = '\0'; //terminate the trimmed string with a null
    return start;
}

bool isSpace(char c) {
    switch (c) {
        case ' ':
        case '\n':
        case '\t':
        case '\f':
        case '\r':
            return true;
            break;
        default:
            return false;
            break;
    }
}
/*iMode 0:ALL,1:Left,2:Right*/
char*Trim(char*szStr、const char ch、int iMode)
{
如果(szStr==NULL)
返回NULL;
char szTmp[1024*10]={0x00};
strcpy(szTmp,szStr);
int-iLen=strlen(szTmp);
char*pStart=szTmp;
char*pEnd=szTmp+iLen;
int i;
对于(i=0;i
我喜欢返回值总是等于参数的情况。这样,如果字符串数组被分配了
malloc()
,它就可以安全地再次被
free()

/* Remove leading whitespaces */
char *ltrim(char *const s)
{
        size_t len;
        char *cur;

        if(s && *s) {
                len = strlen(s);
                cur = s;

                while(*cur && isspace(*cur))
                        ++cur, --len;

                if(s != cur)
                        memmove(s, cur, len + 1);

        }

        return s;
}

/* Remove trailing whitespaces */
char *rtrim(char *const s)
{
        size_t len;
        char *cur;

        if(s && *s) {
                len = strlen(s);
                cur = s + len - 1;

                while(cur != s && isspace(*cur))
                        --cur, --len;

                cur[isspace(*cur) ? 0 : 1] = '\0';
        }

        return s;
}

/* Remove leading and trailing whitespaces */
char *trim(char *const s)
{
        rtrim(s);  // order matters
        ltrim(s);

        return s;
}

这是我的实现,其行为类似于libc中的内置字符串函数(即,它需要一个c字符串,它修改它并将其返回给调用方)

它修剪前导空格并在从左到右解析字符串时将剩余字符向左移动。然后标记字符串的新结尾并开始向后解析,用“\0”替换尾随空格,直到找到非空格字符或字符串的开头。我相信这是这部分的最小可能迭代次数非常规任务

// ----------------------------------------------------------------------------
// trim leading & trailing spaces from string s (return modified string s)
// alg:
// - skip leading spaces, via cp1
// - shift remaining *cp1's to the left, via cp2
// - mark a new end of string
// - replace trailing spaces with '\0', via cp2
// - return the trimmed s
//
char *s_trim(char *s)
{
    char *cp1;                              // for parsing the whole s
    char *cp2;                              // for shifting & padding

    // skip leading spaces, shift remaining chars
    for (cp1=s; isspace(*cp1); cp1++ )      // skip leading spaces, via cp1
        ;
    for (cp2=s; *cp1; cp1++, cp2++)         // shift left remaining chars, via cp2
        *cp2 = *cp1;
    *cp2-- = 0;                             // mark new end of string for s

    // replace trailing spaces with '\0'
    while ( cp2 > s && isspace(*cp2) )
        *cp2-- = 0;                         // pad with '\0's

    return s;
}

这不是最好的方法,但很有效

char* Trim(char* str)
{
    int len = strlen(str);
    char* buff = new char[len];
    int i = 0;
    memset(buff,0,len*sizeof(char));
    do{
        if(isspace(*str)) continue;
        buff[i] = *str; ++i;
    } while(*(++str) != '\0');
    return buff;
}

谢谢。我发现没有库函数是愚蠢的(如果每个人都使用自己的库函数,那么他们都会以各种不同的方式错误处理unicode等)C++的字符串处理是很难的,更不用说Unicode。C++用STD::字符串,但字符串自然需要重新设计。C,尽管它有很多优点,但远不是一个完美的语言。HEH.C是在72发明的。直到90年代Unicode才出现。对于大多数C的历史来说,没有任何BU。t ASCII,str[x]='\0';可以很好地完成这项工作。如果你删除一个新的缓冲区,然后将其复制回来,这很难“原地修改”。就界面而言,它已经原地修改了。是的,祝你在下次面试中卖掉它:)为什么这么复杂?为什么不从一行循环到第一个非空字符并用0替换空格?这段代码效率很低。这是Java的编码方式,而不是C one。malloc可以防止就地函数对输入大小敏感?抱歉,这是错误的。调用strlen两次也会丢失单通参数。尽管速度很慢呃,更长的时间,你的函数实际上甚至不工作。修剪函数什么时候去除单词之间的空格?哦,我认为这会导致缓冲区不足,考虑这个:char缓冲器[]=;修剪(缓冲区);然后你至少读取缓冲器[-1 ]。,如果它是一个随机的空白,你甚至会写出缓冲区的另一面。很好!我已经为此添加了额外的检查。还会检查我的生产代码:)哎哟。这太糟糕了。它看起来也会删除内部空格。“foo bar”应该修剪为“foo bar”,而不是“foobar”,即使没有
sz1:[MQRFH] 9
sz2:[MQRFH] 6
sz3:[MQR FH] 8
sz4:[MQRFH] 7
sz5:[MQRFH] 5
sz6:[M] 1
sz7:[M] 2
sz8:[M] 2
sz9:[] 0
sz10:[] 8
static inline void ut_trim(char * str) {
   char * start = str;
   char * end = start + strlen(str);

   while (--end >= start) {   /* trim right */
      if (!isspace(*end))
         break;
   }
   *(++end) = '\0';

   while (isspace(*start))    /* trim left */
      start++;

   if (start != str)          /* there is a string */
      memmove(str, start, end - start + 1);
}
/* Remove leading whitespaces */
char *ltrim(char *const s)
{
        size_t len;
        char *cur;

        if(s && *s) {
                len = strlen(s);
                cur = s;

                while(*cur && isspace(*cur))
                        ++cur, --len;

                if(s != cur)
                        memmove(s, cur, len + 1);

        }

        return s;
}

/* Remove trailing whitespaces */
char *rtrim(char *const s)
{
        size_t len;
        char *cur;

        if(s && *s) {
                len = strlen(s);
                cur = s + len - 1;

                while(cur != s && isspace(*cur))
                        --cur, --len;

                cur[isspace(*cur) ? 0 : 1] = '\0';
        }

        return s;
}

/* Remove leading and trailing whitespaces */
char *trim(char *const s)
{
        rtrim(s);  // order matters
        ltrim(s);

        return s;
}
// ----------------------------------------------------------------------------
// trim leading & trailing spaces from string s (return modified string s)
// alg:
// - skip leading spaces, via cp1
// - shift remaining *cp1's to the left, via cp2
// - mark a new end of string
// - replace trailing spaces with '\0', via cp2
// - return the trimmed s
//
char *s_trim(char *s)
{
    char *cp1;                              // for parsing the whole s
    char *cp2;                              // for shifting & padding

    // skip leading spaces, shift remaining chars
    for (cp1=s; isspace(*cp1); cp1++ )      // skip leading spaces, via cp1
        ;
    for (cp2=s; *cp1; cp1++, cp2++)         // shift left remaining chars, via cp2
        *cp2 = *cp1;
    *cp2-- = 0;                             // mark new end of string for s

    // replace trailing spaces with '\0'
    while ( cp2 > s && isspace(*cp2) )
        *cp2-- = 0;                         // pad with '\0's

    return s;
}
/* Function to remove white spaces on both sides of a string i.e trim */

void trim (char *s)
{
    int i;

    while (isspace (*s)) s++;   // skip left side white spaces
    for (i = strlen (s) - 1; (isspace (s[i])); i--) ;   // skip right side white spaces
    s[i + 1] = '\0';
    printf ("%s\n", s);
}
void ltrim(char str[PATH_MAX])
{
        int i = 0, j = 0;
        char buf[PATH_MAX];
        strcpy(buf, str);
        for(;str[i] == ' ';i++);

        for(;str[i] != '\0';i++,j++)
                buf[j] = str[i];
        buf[j] = '\0';
        strcpy(str, buf);
}
char* Trim(char* str)
{
    int len = strlen(str);
    char* buff = new char[len];
    int i = 0;
    memset(buff,0,len*sizeof(char));
    do{
        if(isspace(*str)) continue;
        buff[i] = *str; ++i;
    } while(*(++str) != '\0');
    return buff;
}