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

字符串内存图如下:

引入头文件:

 1 #include<stdlib.h>
 2 #include<stdio.h>
 3 #include<string.h>

 函数原型:

1 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';
}

复制代码

实现方法二:

复制代码

 1 void trim(char *strIn, char *strOut){
 2 
 3     char *start, *end, *temp;//定义去除空格后字符串的头尾指针和遍历指针
 4     
 5     temp = strIn;
 6 
 7     while (*temp == ' '){
 8         ++temp;
 9     }
10 
11     start = temp; //求得头指针
12 
13     temp = strIn + strlen(strIn) - 1; //得到原字符串最后一个字符的指针(不是'\0')
14 
15     printf("%c\n", *temp);
16 
17     while (*temp == ' '){
18         --temp;
19     }
20 
21     end = temp; //求得尾指针
22     
23 
24     for(strIn = start; strIn <= end; ){
25         *strOut++ = *strIn++;
26     }
27 
28     *strOut = '\0';
29 }

复制代码

测试:

复制代码

 1 void main(){
 2     char *strIn = "   ak kl  p  ";
 3 
 4     char strOut[100];
 5 
 6     trim(strIn, strOut);
 7 
 8     printf("*%s*\n",strOut);
 9 
10     system("pause");
11 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值