[英]C - Array of strings to an array of char
In C, I need to take a single string argument from argv []
and put it into another array so that I can iterate over the chars. 在C语言中,我需要从
argv []
获取一个字符串参数,并将其放入另一个数组中,以便可以遍历char。 How do I do this? 我该怎么做呢?
(this is to implement a Veginere Cypher FYI) (这是为了实施Veginere Cypher FYI)
If you want to iterate over the characters of the n
th entry in argv
: 如果要遍历
argv
中第n
个条目的字符:
int i;
int len = strlen(argv[n]);
for (i = 0; i < len; i++)
// do something with argv[n][i]
If you want to copy them somewhere else first (which is most likely not necessary) use strcpy()
or strdup()
. 如果要先将它们复制到其他地方(这很有可能不是必须的),请使用
strcpy()
或strdup()
。
You do not need to copy it into a separate string. 您无需将其复制到单独的字符串中。
Here is how: 方法如下:
// argv is array of strings, or array of array of chars
int main( int argc, char** argv ) // here argv is an array of strings
{
int i = 0;
while( 1 )
{
if( argv[1][i] == '\0' )
break; // argv[1][i] <- Current character of the first cmd-line arg
i++
}
}
or if you would really like to copy it to use a simple string, just set up a pointer to the start of the string like so: 或者,如果您真的想将其复制为使用简单的字符串,则只需设置指向字符串开头的指针,如下所示:
char* firstArgument = argv[n]; // where n is the nth command line argument
You don't need to copy the string. 您不需要复制字符串。 You don't state that you are mutating the string (though argv is modifiable, I would probably leave it alone), so just iterate over it.
您没有声明要对字符串进行突变(尽管argv是可修改的,但我可能会不理会它),因此只需对其进行迭代。
int main(int argc, char *argv[])
{
if(argc < some_min_value) {
print_usage();
return -1;
}
for(int i = 0; argv[str_idx][i]; ++i) {
char c = argv[str_idx][i];
/* do something with c */
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.