[英]C - How to copy part of an array of string into another?
Is there a simple and elegant way to split an array from an index?有没有一种简单而优雅的方法可以从索引中拆分数组?
In my program I am getting a array of strings (argv), and I want to ignore the program name and some of its arguments, copying the rest in an array.在我的程序中,我得到了一个字符串数组 (argv),我想忽略程序名称及其一些参数,将其余部分复制到一个数组中。
For example, the content of argv
is {"program_name", "-o", "file1", "file2"}
比如argv
的内容是{"program_name", "-o", "file1", "file2"}
I want to retrieve "file1"
and "file2"
in an array just to make an easy iteration over it.我想在数组中检索"file1"
和"file2"
,以便对其进行简单的迭代。
// PSEUDO
char *files[argc - 2] = argv.split(2, argc - 2)
Any ideas?有任何想法吗?
You can use pointer arithmetic to make it in an elegant way:您可以使用指针算法以优雅的方式实现:
char** filenames = argv + 2;
Just be sure that you have at least 2 arguments before your filenames as you wish.只要确保您的文件名前至少有 2 个参数即可。
#include <stdio.h>
int main(int argc, char** argv) {
if(argc > 2){
//char** that points to the first filename
char** filenames = argv + 2;
//number of filenames available to iterate
int num_of_filenames = argc - 2;
//Printing each name
int i = 0;
for(i = 0; i < num_of_filenames; i++){
printf("%s\n",filenames[i]);
}
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.