我正在尝试编写一个使用指针将字母更改为两个星号(*)的函数。

例如:


  输入:hello12345good++//--ok
  
  输出:**********123456********++//--****


我已经写了一个将字母更改为两个相同字母的字母,但是对于*却不能写相同的字母。

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

int points_converter(char str[])
{
    char *s, *s1;
    int f = 0;

    for (s = str; *s; s++)
    {
        if(isalpha(*s))
        {
            f = 1;
            s1 = s;
            s = s + strlen(s);
            while(s != s1 - 1)
                *(s+1) = *(s--);
            s = s + 2;
        }
    }
    return f;
}

int main()
{
    char str[81];
    int f;
    puts("Input string:");
    while (strlen(gets(str)) >= 81);

    f = points_converter(str);
    if (f == 0)
    {
        puts("No latin letters in string.");
    }
    else
    {
        puts("New string: ");
        puts(str);
    }
    return 0;
}

最佳答案

像这样

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

bool points_converter(char str[]){
    bool f = false;
    char *temp = malloc(strlen(str)*2+1);
    char *s = str, *d = temp;

    if(!temp){
        perror("malloc:");
        return f;//no change
    }
    for (; *s; s++){
        if(isalpha((unsigned char)*s)){
            f = true;
            *d++ = '*';
            *d++ = '*';
        } else {
            *d++ = *s;
        }
    }
    *d = 0;
    strcpy(str, temp);//`str` must have enough spaces.
    free(temp);
    return f;
}

#define MAX_LENGTH 40

int main(void){
    char str[MAX_LENGTH * 2 + 1];

    while(true){
        puts("Input string:");
        fgets(str, MAX_LENGTH+1+1, stdin);//+1:newline, +1:NUL. Use fgets instead of gets
        char *p = strchr(str, '\n');
        if(p){
            *p = '\0';//chomp newline
            break;
        } else {
            while (getchar() != '\n');//Input too long, clear input
        }
    }

    if (points_converter(str)) {
        puts("New string: ");
        puts(str);
    } else {
        puts("No latin letters in string.");
    }
    return 0;
}

08-17 00:52