问题
I am new to C.
I have a code that reads first word from the line, Here is a piece of it:
scanf(Line, "%s", Word);
printf("%s\n", Word);
This code reads and prints the first word in the line. However, I need to compare the first word of the line to another word. Any suggestions?
回答1:
strcmp(str1,str2)
Compares the C string str1 to the C string str2.
This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
Returns an integral value indicating the relationship between the strings:
- A zero value indicates that both strings are equal.
- A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2;
- A value less than zero indicates the opposite.
回答2:
Use strcmp(firststring, secondstring)
it will return 0
, 1
, or -1
.
If both strings are identical then the strcmp()
function will return 0
.
If the first character that does not match has a greater value in firststring
, it will return 1
.
Otherwise, it will return -1
.
回答3:
Take a look at strcmp
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1057537653&id=1043284385
回答4:
You're looking to split words based on some character. In this case ' '. You should be finding the index of the space and then storing the two words into two new strings.
来源:https://stackoverflow.com/questions/12541094/string-comparison