简体   繁体   English

替换C中字符串中的字符

[英]Replacing characters in strings in C

I have recently started using C and am having trouble understanding the use of "&" and "*" and where to put them in my code.我最近开始使用 C,但在理解“&”和“*”的用法以及将它们放在我的代码中的位置时遇到了麻烦。 The current assignment I have requires me to take two inputs, the character in a string that a user would like to swap and the new character to replace it with.我当前的任务要求我接受两个输入,一个是用户想要交换的字符串中的字符,另一个是用来替换它的新字符。 I am not allowed to use the String library.我不允许使用 String 库。 Here is my current code but for some reason, the output is never able to access "replacementchar[0]" and I have no clue why.这是我当前的代码,但由于某种原因,输出永远无法访问“replacementchar [0]”,我不知道为什么。 Any help would be appreciated.任何帮助,将不胜感激。 Thank you!谢谢!

if(response[0] == yes[0]){
        char replacechar[1];
        printf("What character do you want to replace: ");
        scanf("%s", replacechar);

        char newchar[1];
        printf("What is the replacement character: ");
        scanf("%s", newchar);

        printf("you want to replace %c with %c \n", replacechar[0], newchar[0]);
        for(int i = len-1; i > -1; --i){
            if(word[i] == replacechar[0] && word[i] != '\0'){
                printf("found one\n");
                word[i] = newchar[0];
            }
        }
    }

In C, * and & are pointer operators.在 C 中,* 和 & 是指针运算符。 * is used to create pointers variables and dereference them. * 用于创建指针变量并取消对它们的引用 & is used to get the memory address of something. & 用于获取某物的内存地址。

The following code (1) creates an int a, (2) creates an int pointer p using * and (3) sets the value of pointer p to the memory address of a using &.下面的代码 (1) 创建一个 int a,(2) 使用 * 创建一个 int 指针 p 和 (3) 使用 & 将指针 p 的值设置为 a 的内存地址

int a;
int *p;
p = &a;

printf("%d", p);
printf("%d", *p);

The first print will return the value of p, which is the memory address of a.第一次打印将返回 p 的值,即 a 的内存地址。 In the second print we dereference p, which gives us the data stored at that memory address--the value of int a.在第二个打印中,我们取消引用p,它为我们提供了存储在该内存地址的数据——int a 的值。

There are other ways to use pointers.还有其他使用指针的方法。 When you create an array...创建数组时...

int arr[10];

...you are implicitly creating a pointer ("arr") to the first element in your array. ...您正在隐式地创建一个指向数组中第一个元素的指针(“arr”)。 You can access elements if the array in several ways.您可以通过多种方式访问​​数组中的元素。

arr[5]
*(arr + 5)

Both get the 5th element of the array by looking at arr (the memory address of the first element) and adding 5, which gives us the memory address of the 5th element, then dereferencing that with * to get the value of the 5th element.两者都通过查看 arr(第一个元素的内存地址)并加上 5 来获得数组的第 5 个元素,这为我们提供了第 5 个元素的内存地址,然后用 * 取消引用它以获得第 5 个元素的值。

... ...

Your code is wrong not because of a misuse of & and *, but because of the behavior of scanf (which you shouldn't really use).您的代码错误不是因为滥用了 & 和 *,而是因为 scanf 的行为(您不应该真正使用它)。 Scanf writes to a buffer, which you then have to copy in order to save the value. Scanf 写入缓冲区,然后您必须复制该缓冲区以保存该值。 Also, considering you're only scanning a single char, there's no need to use a char array.此外,考虑到您只扫描单个字符,因此无需使用字符数组。 Check out this solution:看看这个解决方案:

char buf, replacechar, newchar;
printf("What character do you want to replace: ");
scanf("%c", &buf);
replacechar = buf;

printf("What is the replacement character: ");
scanf("%s", &buf);
newchar = buf;

printf("You want to replace %c with %c\n", replacechar,
newchar);
for (int i = len-1; i > -1; --i) {
    if (word[i] == replacechar && word[i] != '\0') {
    printf("Found one!\n");
    word[i] = newchar;
    }
}

Another approach besides getchar or scanf using either %s or %c is to use fgets .除了使用%s%c getcharscanf之外,另一种方法是使用fgets Here fgets will read up to two characters from stdin .这里fgets将从stdin读取最多两个字符。 If choice[1] is a newline, only one other character was entered.如果choice[1]是换行符,则只输入了一个其他字符。 Otherwise, clear stdin and prompt to try again.否则,清除stdin并提示重试。
The replacement function advances a pointer text through each character of the string until the character pointed to *text is the terminating zero. replacement函数通过字符串的每个字符推进一个指针text ,直到指向*text的字符是终止零。

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

char fgetschar ( void) {
    char choice[3] = "";

    do {
        if ( fgets ( choice, sizeof choice, stdin)) {//read two characters
            if ( '\n' == choice[0]) {//only newline
                printf ( "\nenter a character\n\ttry again\n");
                continue;
            }
            if ( '\n' != choice[1]) {//did not find expected newline
                while ( fgets ( choice, sizeof choice, stdin)) {
                    if ( '\n' == choice[0] || '\n' == choice[1]) {
                        break;
                    }
                }
                choice[1] = 0;//to make the loop repeat
                printf ( "\nenter one character only\n\ttry again\n");
            }
        }
        else {
            fprintf ( stderr, "fgets EOF\n");
            exit ( EXIT_FAILURE);
        }
    } while ( choice[1] != '\n');

    return choice[0];
}

int replacement ( char *text, char find, char sub) {
    int count = 0;

    while ( text && *text) {//not NULL and not terminating zero
        if ( *text == find) {
            *text = sub;
            ++count;
        }
        ++text;//advance to next character
    }

    return count;
}

int main ( void) {
    char replacechar = 0;
    char newchar = 0;
    char word[] = "a b c d e f g h i j k l m n o p q r s t u v w x y z";

    int size = 21;
    int item = rand ( ) % ( size - (int)( size * 0.6));
    printf ( "item %d\n", item);

    printf ( "What character do you want to replace: ");
    fflush ( stdout);
    replacechar = fgetschar ( );
    printf ( "replace character: %c\n\n", replacechar);

    printf("What is the replacement character: ");
    fflush ( stdout);
    newchar = fgetschar ( );
    printf ( "replacement character: %c\n\n", newchar);

    int found = replacement ( word, replacechar, newchar);

    printf ( "found %d instances of %c\n", found, replacechar);

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

    return 0;
}

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

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