合并字符串中的空格


#include "stdio.h"
#include "string.h"
#include "stdlib.h"
 
char* mergeblank(char str[]);
 
int main()
{
    char str[]= "hello       world    this    is     a \"t    e   s    t\"this is     a         test"; 
    printf("str_old: %s\n", str);
    char *p = mergeblank(str);
    printf("str_new: %s\n", p);
    system("pause");
    return 0;
}
 
char* mergeblank(char str[])
{ 
    int iBlank = 0, iPos = 0;
    int i = 0, j=0;
    int bYH = 0;
    for (i=0; str[i]!='\0'; i++)
    {
        if (str[i] == '"')
        {
            if (!bYH)
            {
                bYH = 1;
            }
        else
        {
            bYH = 0;
        }
    }

    if (str[i] == ' ' && !bYH)
    {
        if (iBlank == 0)
        {
            iPos = i;
        }
            iBlank ++;
        }
        else
        {
        //merge blank
        if (iBlank > 1)
        {
            for (j=iPos+1; str[j]!='\0'; j++)
            {
                str[j] = str[j+iBlank-1];
            }    

            i = i-iBlank+1;    
        }   

        iBlank = 0;
        }
    }
    return str;
}

Comments are closed.