首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

从命令行参数打印子字符串,在C中

从命令行参数打印子字符串,在C中可以使用以下代码实现:

代码语言:c
复制
#include<stdio.h>
#include<string.h>

int main(int argc, char *argv[]) {
    if (argc < 3) {
        printf("Usage: %s<string><start_index> <end_index>\n", argv[0]);
        return 1;
    }

    const char *str = argv[1];
    int start_index = atoi(argv[2]);
    int end_index = atoi(argv[3]);

    if (start_index < 0 || end_index >= strlen(str) || start_index > end_index) {
        printf("Invalid indices.\n");
        return 1;
    }

    for (int i = start_index; i <= end_index; i++) {
        printf("%c", str[i]);
    }
    printf("\n");

    return 0;
}

这个程序从命令行参数中获取一个字符串和两个索引值,然后打印出字符串中从起始索引到结束索引之间的子字符串。如果提供的索引无效,程序将输出错误消息并返回非零值。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券