我正在尝试创建一个简单的命令行测试是/不是等值线图(一个单词中没有重复的字母),但我在使用 argv 作为字符数组时遇到了问题。
我做了一些搜索,这个答案使用了 strcopy , 然后给我一个更详细的 malloc answer .可能是因为我糟糕的 google-foo 我找不到循环遍历 argv 字符的示例。我试过的这段代码正在对字符串进行切片?:
/* first argument is the number of command line arguments,
* list of command line arguments, argv[0] == function name
*/
int main(int argc, char *argv[]) {
if(argc != 2){
printf("error, bad arguments!\n");
return 1;
} else {
char* isogram = NULL;
isogram = (char*)malloc(sizeof(argv[1])+1);
strcpy(isogram, argv[1]);
for(int i=0; i<strlen(isogram); i++){
printf("isogram[%d]==%s\n", i, &isogram[i]);
}
// detect_isogram(isogram);
}
return 0;
}
输出:
gcc -o isogram isogram.c -std=c99; ./isogram testing
isogram[0]==testing
isogram[1]==esting
isogram[2]==sting
isogram[3]==ting
isogram[4]==ing
isogram[5]==ng
isogram[6]==g
注意:我尝试了 char *isogram[]=NULL
以为这是我想要初始化的,但正如网站所建议的那样,这只适用于 char *isogram = NULL
.
编辑:我知道如何测试它们,只是无法让每个角色相互比较。每个索引返回 slice[i:]...
for(int i=0; i<strlen(argv[1]); i++){
for(int j=i+1; j<strlen(argv[1]); j++){
printf("isogram[%d]==%s\n", i, &argv[1][i]);
printf("isogram[%d]==%s\n", j, &argv[1][j]);
}
}
最佳答案
您不需要任何argv[1] 处理。您只需要将它传递给检测功能即可。
code00.c:
#include <stdio.h>
#include <string.h>
int detect_isogram(const char *word) {
size_t len = strlen(word), i = 0, j = 0;
for (i = 0; i + 1 < len; i++)
for (j = i + 1; j < len; j++)
if (word[i] == word[j])
return 0;
return 1;
}
int detect_isogram2(const char *word) {
size_t len = strlen(word), i = 0;
for (i = 0; i + 1 < len; i++)
if (strchr(word + i + 1, word[i]))
return 0;
return 1;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("error, bad arguments!\n");
return 1;
} else {
printf("detect_isogram returned: %d\ndetect_isogram2 returned: %d\n", detect_isogram(argv[1]), detect_isogram2(argv[1]));
return 0;
}
}
注意事项:
- 该算法很简单:对于字符串中的每个字符(从第 1 个st 开始,但 不包括最后一个),检查它是否在剩余部分字符串
- 支票可以是:
- 手动(遍历字符串的剩余部分(从搜索到的紧接的字符开始),并比较字符)- detect_isogram
- 通过 [CPPReference]: strchr - detect_isogram2
- 支票可以是:
输出:
root@testserver:/home/cfati/work/so/q048873942# gcc code.c -o isogram root@testserver:/home/cfati/work/so/q048873942# ./isogram testing detect_isogram returned: 0 detect_isogram2 returned: 0 root@testserver:/home/cfati/work/so/q048873942# ./isogram "" detect_isogram returned: 1 detect_isogram2 returned: 1 root@testserver:/home/cfati/work/so/q048873942# ./isogram 1 detect_isogram returned: 1 detect_isogram2 returned: 1 root@testserver:/home/cfati/work/so/q048873942# ./isogram 12345678 detect_isogram returned: 1 detect_isogram2 returned: 1 root@testserver:/home/cfati/work/so/q048873942# ./isogram 123456781 detect_isogram returned: 0 detect_isogram2 returned: 0 root@testserver:/home/cfati/work/so/q048873942# ./isogram qq detect_isogram returned: 0 detect_isogram2 returned: 0
更新#0
- 采纳了@chux的改进建议
关于c - 在 C 中测试等值图 - Argv 到字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48873942/