【C语言】删除字符串中的空格

编写一个函数接受一个字符串作为参数,并删除字符串中的空格。

函数代码

#include <stdio.h>

char *strDelSpace(char *str)
{
    char *pc_inspect = str;
    char *pc_locate = str;

    // 检查两个指针是否指向相同地址且这个地址是否指向空字符
    while (pc_inspect == pc_locate && *pc_inspect)
    {
        // 检测到空格时,inspect指针跳过所有空格,直到指向字符串第一个非空格字符
        if (*pc_inspect == ' ')
        {
            while (*pc_inspect == ' ')
                pc_inspect++;
        }
        else
        {
            pc_inspect++;
            pc_locate++;
        }
    }

    // (inspect和locate指针不再指向同一个地址,即检测到了空格)对字符串逐个进行赋值
    while (*pc_inspect)
    {
        // 跳过空格
        while (*pc_inspect == ' ')
            pc_inspect++;

        *pc_locate = *pc_inspect;

        pc_locate++;
        pc_inspect++;
    }

    // 在字符串末尾添加空字符
    *pc_locate = '\0';

    return str;
}

函数测试

#include <stdio.h>

char *strDelSpace(char *str);

int main(int argc, char const *argv[])
{
    char str1[] = "this is a string";
    char str2[] = "thisanotherstr ing";
    char str3[] = "   thisanotherstr ing";
    
    strDelSpace(str1);
    strDelSpace(str2);
    strDelSpace(str3);

    printf("*%s*\n", str1);
    printf("*%s*\n", str2);
    printf("*%s*\n", str3);

    return 0;
}

char *strDelSpace(char *str)
{
    char *pc_inspect = str;
    char *pc_locate = str;

    // 检查两个指针是否指向相同地址且这个地址是否指向空字符
    while (pc_inspect == pc_locate && *pc_inspect)
    {
        // 检测到空格时,inspect指针跳过所有空格,直到指向字符串第一个非空格字符
        if (*pc_inspect == ' ')
        {
            while (*pc_inspect == ' ')
                pc_inspect++;
        }
        else
        {
            pc_inspect++;
            pc_locate++;
        }
    }

    // (inspect和locate指针不再指向同一个地址,即检测到了空格)对字符串逐个进行赋值
    while (*pc_inspect)
    {
        // 跳过空格
        while (*pc_inspect == ' ')
            pc_inspect++;

        *pc_locate = *pc_inspect;

        pc_locate++;
        pc_inspect++;
    }

    // 在字符串末尾添加空字符
    *pc_locate = '\0';

    return str;
}

输出

>
*thisisastring*
*thisanotherstring*
*thisanotherstring*
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值