c - 反转命令行参数 (C)

标签 c

该程序的总体要点是接受命令行参数,并以可变长度向后打印每个字符串。

例如:

$ ./reversecommand hello 102
dnammocesrever/. olleh 201

我在将思维过程实现为代码时遇到困难(例如下面的 hello)。有什么想法吗?

argc[0] ./reversecommand 
argc[1] hello
argc[1][0] h -> argc[1][4] o
argc[1][1] e -> argc[1][3] l
argc[1][2] l -> argc[1][2] l
argc[1][3] l -> argc[1][1] e
argc[1][4] o -> argc[1][0] h
argc[2] 102
argc[3] [null]

最佳答案

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

static void print_reversed(const char *str, size_t len)
{
    const char *ptr = str + len;
    while (ptr > str)
        putchar(*--ptr);
}

int main(int argc, char **argv)
{
    for (int i = 0; i < argc; i++)
    {
        if (i != 0)
            putchar(' ');
        print_reversed(argv[i], strlen(argv[i]));
    }
    putchar('\n');
    return 0;
}

无需修改字符串;只需以相反的顺序一次打印一个字符即可。

关于c - 反转命令行参数 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35216508/

相关文章:

c - 在 C 中,如何使用字符串数组作为查找表?

c - 返回状态/值的适当范围

C语言用指针将二维数组转为一维数组

c - C 中 typedef 的未知实现

c - OpenSSL BIO_f_base64 不读取整个缓冲区

python - cython结构,从python到cython的字符串

c - 如何在 C 中调用带有 "int"参数的函数?

c - 无法将 C 程序变量绑定(bind)到 SQL Server 中的日期时间类型列

c++ - Vc++(Wince平台)如何打开读取16位.raw文件

c - strcmp() 在 C 中究竟返回什么?