我如何完成K&安培; R练习2-4? [英] How do I complete K&R Exercise 2-4?

查看:127
本文介绍了我如何完成K&安培; R练习2-4?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何编写使用K&放大器在C程序; R书(C编程语言),我有与练习一个问题。它要求我检测并删除在串S的字符,这在字符串s2匹配任何字符。

所以,说S1 =A;

和S2 =AABAACAADAAE

我希望它回归BCDE

我知道我朝它在正确的道路上,我只是不知道如何设计程序非常好,你可以给我任何额外的提示。我试着看了一下二叉搜索树算法,但觉得这是这个平凡的任务有点太超前了。

谢谢大家!

  / *挤压的另一种版本(S1,S2)是删除每一个字符
 * S1,在字符串s2匹配任何字符
 *
 * Angie@odfx.org
 * /#包括LT&;&stdio.h中GT;
#包括LT&;&string.h中GT;无效挤压(char中[],CHAR T []);字符字符串[] =BAD;
烧焦sstring [] =ABC;INT
主要(无效)
{
    挤压(字符串,sstring);
    返回0;
}空虚
挤压(char中[],CHAR T [])
{
    INT I,J,D;    D = 0;
    如果(的strstr(S,T)== NULL)
        的printf(%C,S [I]);
    S [J] ='\\ 0';
}


解决方案

伟大的书。如果我是你,我会继续完全一样的挤()第2.8节,但不是直接的比较(S [I]!= C)我会写,并利用功能

  int包含(char中[],INT C)

如果字符串s包含C,否则为0返回1。先从简单的方法;当它工作,你可以改善与更复杂的解决方案的性能(二进制搜索,但是请注意,这个问题不需要字符S2是在一个特定的顺序)。

I'm learning how to write programs in C using the k&r book (The C Programming Language) and I have a problem with one of the exercises. It's asking me to detect and remove a character in string s1, which matches any characters in the string s2.

So, say s1 = "A";

And s2 = "AABAACAADAAE"

I want it to return "BCDE"

I know I'm on the right path towards it, i just don't know how to design programs very well, could you give me any additional tips. I tried to read about the binary search tree algorithm, but felt it was a little too advanced for this mundane task.

Thanks everyone!

/* An alternate version of squeeze(s1, s2) that deletes each character in
 * s1 that matches any character in the string s2
 *
 * Angie@odfx.org
 */

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

void squeeze(char s[], char t[]);

char string[] = "BAD";
char sstring[] = "ABC";

int
main(void)
{
    squeeze(string, sstring);
    return 0;
}

void
squeeze(char s[], char t[])
{
    int i, j, d;

    d = 0;
    if(strstr(s, t) == NULL)
        printf("%c", s[i]);
    s[j] = '\0';
}

解决方案

Great book. If I were you, I would proceed exactly as for the squeeze() in section 2.8, but instead of a direct comparison (s[i] != c) I would write and exploit a function

 int contains(char s[], int c)

which returns 1 if the string s contains c, 0 otherwise. Start with the simple approach; when it works you may improve performance with more complex solutions (binary search, but note that the problem doesn't require the characters in s2 to be in a particular order).

这篇关于我如何完成K&安培; R练习2-4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆