C: 去掉字符串的左右空格及全部空格

本文介绍了三种C语言去除字符串空格的方法,包括移除左右空格和全部空格,通过示例代码展示具体实现。
摘要由CSDN通过智能技术生成

昨天代码中用到一个小功能,去掉字符串中最右侧的空格,今天闲的无聊,就索性把去掉左侧空格,和去掉字符串中全部空格的方法都写一下吧。

方法一,使用两个变量:

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


int Strim(char *strDst, char *strSrc) {
    int i = 0;
    int y = 0;

    memset(strDst, '\0', sizeof(strDst));
    while(strSrc[i] != '\0') {
        if (strSrc[i] == ' ') {
            i++;
            continue;
        }

        strDst[y] = strSrc[i];
        i++;
        y++;
    }

    return 0;
}

int trim(char *strDst, char *strSrc) {
    int i = 0;
    int j = 0;

    j = strlen(strSrc) - 1;

    while(strSrc[i] == ' ') {
        ++i;
    }

    while(strSrc[j] == ' ') {
        --j;
    }

    strncpy(strDst, strSrc + i, j - i + 1);
    strDst[j - i + 1] = '\0';

    return 0;
}

int Ltrim(char *strDst, char *strSrc) {
    int i =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值