首页 > 后端开发 > C++ > 正文

挤压以从字符串中删除字符。

WBOY
发布: 2024-07-18 04:32:50
原创
1081 人浏览过

squeeze to remove chars from string.

https://www.learntosolveit.com/ is a companion website to learn C programming using K&R book using modern tools. This post discusses exercises and topics from the book.

/**
 * Exercise 2.4
 *
 * Let us write a version of squeeze(s1,s2) that deletes each
 * character in the string 1 that matches any character in the string s2.
 * Utilize user defined function mgetline to input the strings.
 * Don't use any standard library string manipulation function.
 *
 **/

#include <stdio.h>

#define MAXLINE 1000

int mgetline(char s[], int lim);

void squeeze(char s1[], const char s2[]);

int main(void) {
    char s1[MAXLINE], s2[MAXLINE];
    mgetline(s1, MAXLINE);
    mgetline(s2, MAXLINE);

    squeeze(s1, s2);

    printf("\n%s\n", s1);

    return 0;
}

int mgetline(char s[], int lim) {
    int i, c;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
        s[i] = c;

    if (c == '\n')
        s[i++] = c;

    s[i] = '\0';

    return i;
}

void squeeze(char s1[], const char s2[]) {
    int i, j, k;
    k = 0;

    for (i = 0; s1[i] != '\0'; ++i) {
        for (j = 0; (s1[i] != s2[j]) && s2[j] != '\0'; ++j)
            ;
        if (s2[j] == '\0')
            s1[k++] = s1[i];
    }

    s1[k] = '\0';
}

登录后复制

Follow the visual explanation of this program in this post - https://www.learntosolveit.com/cprogramming/chapter2/ex_2.4_squeezess

以上是挤压以从字符串中删除字符。的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板