简体   繁体   English

C - 如何将字符串数组的一部分复制到另一个字符串中?

[英]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.

相关问题 如何将数组的一部分从2d数组复制到C中的另一个数组中 - How to copy part of an array from a 2d array into another array in C 如何将字符串的一部分复制到struct数组的元素? - How to copy a part of a string to an element of array of struct? 如何将单个字符从字符串数组复制到“ C”中的另一个字符串 - How to copy single chars from an array of strings to another string in “C” c语言如何将字符串拆分成相等大小的部分并将其复制到临时字符串数组中以进行进一步处理? - How to split string in equal size part and copy it to temporary string array for further processing in c language? 如何将字符串的一部分复制到另一个字符串中? - How can I copy part of a string into another string? 如何将分配的字符串复制到 C 中的另一个字符串中 - How to copy a malloced string into another string in C 如何将字符串的一部分复制到另一个变量? - How can i copy part of a string to another variable? 如何使用指针将字符数组复制到&#39;c&#39;中的另一个字符数组中,而不使用字符串库 - How to copy a character array into another character array in 'c' using pointers and without using string library 将字符串复制到另一个C中 - copy a string into another C 如何在C中将一个数组的数据复制到另一个数组? - How to copy data of one array to another in C?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM