我想计算空格,比如' ' (ASCII或32)。我必须使用命令行传递参数。例如,我输入Hello World并希望接收空格的数量,在这种情况下,结果应该是2。
我已经试过了: Text = Hello World
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]){
int spaces = 0;
char* mystring = argv[1];
int size = strlen(argv[1]) + strlen(argv[2]);
for(int i = 0; i < size; i++){
if((*(mystring + i)) == ' '){
spaces++;
printf("%d\n", spaces);
}
}
}我知道*(argv + 1)是Hello (或ASCII码)和*(argv + 2) = World,这就是我的问题所在。如何计算argv[n]之间的空格?空格的数量可以不同,因此我不想像If(argc > 1){ spaces++;}那样编写代码。
有人能帮帮忙吗?
诚挚的问候,
凯塔
发布于 2019-12-26 16:14:12
如果执行以下命令:
$ a.out Hello world # There are 5 spaces between both args here.shell将通过将输入命令拆分成空格(空格、制表符和/或换行符的连续序列)位置的参数来提取命令的参数,并从输入中删除注释(如上面的一个),因此如果您发出上面的命令,您将得到如下的argv:
int argc = 3;
char *argv[] = { "a.out", "Hello", "world", NULL, };如果使用引号分隔参数,可以发出
$ a.out "Hello world" # there are also 5 spaces between the words.在这种情况下,你会得到类似这样的结果:
int argc = 2;
char *argv[] = { "a.out", "Hello world", NULL, };在这种情况下,您可以将空格放入参数中。
重要
您不会检查传递给a.out的参数数量,因此在您发布的情况下,您可能会尝试将NULL指针传递给strlen(),这将导致未定义的行为。这是一个错误,为了让您的程序正常工作,您可以执行以下操作(我已经更正了一些其他错误,并在代码的注释中对它们进行了注释):
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
int spaces = 0;
int arg_ix; /* index of the argument to consider */
for (arg_ix = 1; arg_ix < argc; arg_ix++) { /* so we don't check more arguments than available */
char *mystring = argv[arg_ix];
int size = strlen(mystring);
for(int i = 0; i < size; i++) {
if(mystring[i] == ' '){ /* why use such hell notation? */
spaces++;
}
}
}
printf("%d\n", spaces); /* print the value collected at the end, not before */
}这段代码可以被简化(利用mystring是一个指针,通过这种方法移动指针直到我们到达字符串的末尾(指向\0字符)(它还避免了计算字符串长度,这使得字符串上的另一次传递-没有必要)
#include <stdio.h>
/* string.h is not needed anymore, as we don't use strlen() */
int main(int argc, char* argv[]){
int spaces = 0;
int arg_ix;
for (arg_ix = 1; arg_ix < argc; arg_ix++) {
char* mystring = argv[arg_ix];
for( /* empty */; *mystring != '\0'; mystring++) {
if(*mystring == ' '){
spaces++;
}
}
}
printf("%d\n", spaces);
}最后,您有一个带有isspace(c)等函数的<ctype.h>标头,用于检查字符是否为空格(在本例中,它检查空格和制表符。
#include <stdio.h>
#include <ctype.h>
int main(int argc, char* argv[]){
int spaces = 0;
int arg_ix;
for (arg_ix = 1; arg_ix < argc; arg_ix++) {
char* mystring = argv[arg_ix];
for(; *mystring != '\0'; mystring++) {
if(isspace(*mystring)){
spaces++;
}
}
}
printf("%d\n", spaces);
}发布于 2019-12-22 21:30:51
将字符串放在双引号中,如"Hello World“。
https://stackoverflow.com/questions/59444553
复制相似问题