首頁 > 後端開發 > C++ > 主體

擠壓以從字串中刪除字元。

WBOY
發布: 2024-07-18 04:32:50
原創
869 人瀏覽過

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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!