模型-删除空格

求非空字符串长度,两头堵,

 i = 0;
 j = strlen(p) - 1;
i++,j--,len = j-i;
去除空格,保留新字符串
 strncpy(newstr, str+i, ncount);

  char *p = "    abcdefg    ";   //p所指向的内存空间在全局区,不能被修改
 char buf2[1024] = "    abcdefg    ";
//重新定义在临时区才能对其进行修改
    strncpy(str, str+i, ncount); 


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

//求非空格的字符串长度
void getcount(char *str, int *pCount)
{
    
    char *p = str;
    int ncount = 0;
    int i,j = 0;
    i = 0;
    j = strlen(p) - 1;
    if(str == NULL || pCount == NULL)
    {
        return;
    }
    while(isspace(p[i]) && p[i] != '\0')
    {
        i++;
    }
    while(isspace(p[j]) && p[j] != '\0')
    {
        j--;
    }
    ncount = j - i + 1;
    *pCount = ncount;

    
    return;
}
//去除字符串两端的空格
int trimSpace(char *str, char *newstr)
{
    char *p = str;
    int ncount = 0;
    int i,j = 0;
    i = 0;
    j = strlen(p) - 1;
    if(str == NULL || newstr == NULL)
    {
        return;
    }
    while(isspace(p[i]) && p[i] != '\0')
    {
        i++;
    }
    while(isspace(p[j]) && p[j] != '\0')
    {
        j--;
    }
    ncount = j - i + 1;

    strncpy(newstr, str+i, ncount);
    newstr[ncount] = '\0';
    return 0;
}

//去除字符串两端的空格
//*str指针所指向的内存空间能否修改?
int trimSpace02(char *str)
{
    char *p = str;
    int ncount = 0;
    int i,j = 0;
    i = 0;
    j = strlen(p) - 1;
    if(str == NULL )
    {
        return;
    }
    while(isspace(p[i]) && p[i] != '\0')
    {
        i++;
    }
    while(isspace(p[j]) && p[j] != '\0')
    {
        j--;
    }
    ncount = j - i + 1;

    //str所指向的内存空间在全局区,不能被修改
    //重新定义在临时区才能对其进行修改
    strncpy(str, str+i, ncount); 
    str[ncount] = '\0';
    return 0;
}
int main(void)
{
    char *p = "    abcdefg    ";
    char buf[1024] = {0};
    char buf2[1024] = "    abcdefg    ";
    int count = 0;
    getcount(p, &count);

    trimSpace(p, buf);
    //trimSpace02(p);/str所指向的内存空间在全局区,不能被修改
    trimSpace02(buf2);//重新定义在临时区才能对其进行修改

    printf("count =  %d\n", count);
    printf("buf: %s\n", buf);
    printf("p: %s\n", p);

    return 0;

}

 

posted @ 2017-04-30 15:28  Liu_Jing  Views(177)  Comments(0)    收藏  举报