0

我一直在尝试将一个字符串“复制”到另一个字符串,相反。它有点工作,但它打印了一些奇怪的符号。我试过设置 char copy[length2] 但这会使程序根本不运行。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define ARR_SIZE 50

int main()
{
    char string[ARR_SIZE];
    printf("Enter char array!\n");
    fgets(string, ARR_SIZE, stdin);

    string[strlen(string) - 1] = '\0';
    int length = (strlen(string) - 1);
    int length2 = (strlen(string) - 1);

    printf("%s\t%d\n", string, length);

    for (int i = 0; i <= length; i++)
    {
        printf("INDEX = %d   CHAR = %c\n", i, string[i]);
    }
    
    printf("%d", length2);
    char copy[ARR_SIZE];
    
    for (int i = 0; i <= length2; i++)
    {
        copy[i] = string[length];
        length--;
    }

    


    printf("\n%s", copy);
}

在此处输入图像描述

4

2 回答 2

1

这些是我对您的代码所做的最小修改:

#include <stdio.h>
#include <string.h>
// remove unneeded headers

#define ARR_SIZE 50

int main(void)
{
    char string[ARR_SIZE];
    printf("Enter char array!\n");
    fgets(string, ARR_SIZE, stdin);

    string[strlen(string) - 1] = '\0';
    // remove the -1 on the string length calculation, the NUL terminator is not
    // included in strlen's return value
    int length = strlen(string);
    // no sense in calling strlen twice
    int length2 = length;

    // fixed `length` now prints the correct length
    printf("%s\t%d\n", string, length);

    // change from <= to <. The array indices where the characters live are
    // [0, length-1].
    for (int i = 0; i < length; i++)
    {
        printf("INDEX = %d   CHAR = %c\n", i, string[i]);
    }
    
    // fixed `length2` now prints the correct length
    printf("%d", length2);
    char copy[ARR_SIZE];
    
    for (int i = 0; i < length2; i++)
    {
        // last character in `string` lives at the `length`-1 index
        copy[i] = string[length-1];
        length--;
    }

    // `length2` is the index after the last char in `copy`, this needs
    // to be NUL terminated.
    copy[length2] = '\0';

    // prints the reversed string
    printf("\n%s", copy);
}

演示

于 2021-11-02T16:10:28.193 回答
0
  1. 使用函数。
  2. 用空字符\0或简单地终止字符串0
char *copyreverse(char *dest, const char *src)
{
    size_t len = strlen(src);
    const char *end = src + len - !!len;
    char *wrk = dest;

    while(len--)
        *wrk++ = *end--;
    *wrk = 0;
    return dest;
}

int main()
{
    char dest[10];
    char *src = "hello";

    printf("`%s` reversed `%s`\n", src, copyreverse(dest, src));
}
于 2021-11-02T15:39:55.453 回答