在我的代码中,我想使用表示 Will、Bob、Billy、Ryan 或 Ed 的字符串而不是 int。具体来说,使用 N 个字符串 S[1],S[2]...S[N],其中 S[I] 是上面的名称。
此外,输入 N 的限制如下:(1 ≤ N ≤ 100,000)
#include <stdio.h>
int main(void)
{
int input_num=0;
int isWill = 0;
int isBob = 0;
int isBilly = 0;
int isRyan = 0;
int isEd = 0;
int n=0;
scanf("%d", input_num);
printf("%d", input_num);
for(n;n<input_num;n++)
{
char tmp[100,000];
scanf("%s", tmp);
if(tmp == "Will")
isWill = 1;
else if(tmp == "Bob")
isBob = 1;
else if(tmp == "Billy")
isBlue = 1;
else if(tmp == "Ryan")
isRyan = 1;
else if(tmp == "Ed")
isEd = 1;
}
//end of input
if(isWill == 0)
printf("Will\n");
if(isBob == 0)
printf("Bob\n");
if(isBilly == 0)
printf("Billy\n");
if(isRyan == 0)
printf("Ryan\n");
if(isEd == 0)
printf("Ed\n");
return 0;
}
最佳答案
要比较字符串,您需要使用 strcmp
库函数,如果两个参数字符串相等,该函数将返回 0:
if ( strcmp( tmp, "Will" ) == 0 )
// tmp contains the string "Will"
如果您想要一个字符串数组,可以采用以下两种方法之一。您可以声明一个二维数组,其中第一个维度是名称的数量,第二个维度是名称的最大长度:
char names[NUMBER_OF_NAMES][MAX_NAME_LENGTH+1];
要复制字符串,请使用strcmp
:
strcmp( names[0], "Will" );
strcmp( names[1], "Bob" );
// etc.
或者,您可以声明一个一维数组,其中每个元素都是指向字符串的指针:
char *names[NUMBER_OF_NAMES];
names[0] = "Will";
names[1] = "Bob";
请注意,您正在将一个指针值分配给names[i]
;您没有将字符串内容复制到 names[i]
。
最后,C 无法识别像 100,000
这样的整数文字;您需要将 tmp
缓冲区声明为
char tmp[100000];
尽管这对于字符串缓冲区来说有点大。
关于C:将 int 转换为 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26187306/