美文网首页
C语言实现去除字符串首尾空格

C语言实现去除字符串首尾空格

作者: 路飞仙贝 | 来源:发表于2020-01-08 10:21 被阅读0次

转载:https://www.cnblogs.com/zhouquan-1992-04-06/p/6200784.html

图1
#include<stdlib.h>
#include<stdio.h>
#include<string.h>

void trim(char *strIn /*in*/, char *strOut /*in*/);

// 方法一
void trim(char *strIn, char *strOut){

    int i, j ;

    i = 0;

    j = strlen(strIn) - 1;

    while(strIn[i] == ' ')
        ++i;

    while(strIn[j] == ' ')
        --j;
    strncpy(strOut, strIn + i , j - i + 1);
    strOut[j - i + 1] = '\0';
}

// 方法二
void trim(char *strIn, char *strOut){

    char *start, *end, *temp;//定义去除空格后字符串的头尾指针和遍历指针
    
    temp = strIn;

    while (*temp == ' '){
        ++temp;
    }

    start = temp; //求得头指针

    temp = strIn + strlen(strIn) - 1; //得到原字符串最后一个字符的指针(不是'\0')

    printf("%c\n", *temp);

    while (*temp == ' '){
        --temp;
    }

    end = temp; //求得尾指针
    

    for(strIn = start; strIn <= end; ){
        *strOut++ = *strIn++;
    }

    *strOut = '\0';
}


//测试
void main(){
    char *strIn = "   ak kl  p  ";

    char strOut[100];

    trim(strIn, strOut);

    printf("*%s*\n",strOut);

    system("pause");
}

相关文章

网友评论

      本文标题:C语言实现去除字符串首尾空格

      本文链接:https://www.haomeiwen.com/subject/tgbjactx.html