简体   繁体   English

用c从字符串中删除一些空格

[英]removing a few whitespaces from string with c

First my code printed yksi itsekseen lol and now it prints yksiitsekseenlol and I am trying to print yksi itsekseen lol .首先我的代码打印yksi itsekseen lol ,现在它打印yksiitsekseenlol ,我正在尝试打印yksi itsekseen lol In the first one there are two and second there's none and I'm trying to have there only one space between the words.在第一个中有两个,第二个没有,我试图在单词之间只有一个空格。

My code:我的代码:

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

void antikorso(char *dest, const char *src) {
    const char *p = src;
    int i;

    for (i = 0; *p != '\0'; i++, p++)
    {
        if (*p == 'x') {
            dest[i++] = 'k';
            dest[i] = 's';
        }
        else if (*p == 'z') {
            dest[i++] = 't';
            dest[i] = 's';
        }
        else
        {
            dest[i] = *p;
        }
    }
    dest[i] = '\0';
    char *original = dest;
    char c[10] = "hello";
    while (dest = strstr(dest, c)) {
        memmove(dest, dest + strlen(c), 1 + strlen(dest + strlen(c)));
    }

    char *nat = original;
    char b[20] = "asd";
    while (dest = strstr(original, b)) {
        memmove(dest, dest + strlen(b), 1 + strlen(dest + strlen(b)));
    }
    printf("\n%s", nat);

    char *vit = nat;
    char d[10] = "  ";
    while (dest = strstr(nat, d)) {
        memmove(dest, dest + strlen(d), 1 + strlen(dest + strlen(d)));
    }
    printf("\n%s", vit);
    return vit;
    }



int main(void)
    {

    const char *lol = "hello yxi asd izexeen hello lol";
    char asd[10000];
    antikorso(asd, lol);

    }

Ok, so you almost have it I think, change好的,所以你几乎拥有它,我想,改变

memmove(dest, dest + strlen(c), 1 + strlen(dest + strlen(c)));

to

memmove(dest, dest + strlen(c) - 1, 1 + strlen(dest + strlen(c)));

I think that will do it.我认为这会做到。 The code was previously skipping two spaces, so if you back it up one spot, it should include one space in the copy.该代码之前跳过了两个空格,因此如果您将其备份一个位置,它应该在副本中包含一个空格。

That should work for collapsing two spaces down to one space anyway.无论如何,这应该适用于将两个空间折叠为一个空间。 You should test what happens if you end up with three spaces in a row.您应该测试一下如果连续出现三个空格会发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM