开发者

c - comparing strings

The function below 开发者_如何学编程should be replacing characters found in s with spaces if they are found in toBlank:

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

/* function blank replaces all characters in the parameter string s
 * that are present in the parameter string toBlank with space characters.
 * for example, if s were the string "abcdef" and toBlank the string
 * "bde", then after calling this function, s would be "a c  f" */
void blank(char *s, const char *toBlank){
    int i=0, j=0;
    while (s[i] != '\0'){
        if (s[i] == toBlank[j]){
            s[i] = ' ';
        }else{
            j++;
        }
        i++;

    }
    printf("%s", s);
}

int main(void){
    blank("abcdef", "bde");
}

The problem is, s is never being modified. Can someone explain what's happening?


You're passing a string literal (which is effectively const) as your first parameter, and you then try to modify it within the function.

Do this instead:

int main(void)
{
    char s[] = "abcdef";

    blank(s, "bde");

    return 0;
}


I think you need to iterate over the characters in toBlank.

void blank(char *s, const char *toBlank)
{
    int i=0, j;
    while (s[i] != '\0')
    {
        j = 0;
        while(toBlank[j] != '\0')
        {
          if (s[i] == toBlank[j])
          {
              s[i] = ' ';
              break;
          }
          else
          {
              ++j;
          }
        }
        ++i;
    }
    printf("%s", s);
}


/* there are stdlib functions for these kind of things */

#include <stdlib.h>
void blank(char *str, char * wits)
{
size_t pos,len;

for (pos=len=0; str[pos]; pos += len) {
    len = strspn(str+pos, wits);
    if (len) memset(str+pos, ' ', len);
    else len = strcspn(str+pos, wits);
    }
}


don't you want the j++ inside the if and not the else? I thought you progress when you find the char

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜