问题描述
char names [MAX_CLASS_SIZE][MAX_NAME_SIZE+1]={"Julias Hoffman","Dianne Conner","Mitchell Cooper","Johnnie Greene","Johanna Mason","Kevin Adkins","Brandi Spencer","Marian Tyler","Chester Cross","Martin Lawrence","Jane Smith","Sara Jones"};
char specificName[]="";
int search(char names[][MAX_NAME_SIZE+1],char specificName[])
for(i=0;i<MAX_CLASS_SIZE;i++){
if (strcmp(names[i],specificName)==0)
{
printf("Found %s",names[i]);
return i;
}
}
这个函数接收一个字符串数组,称为名称和
这再次$ P $字符数组psents特定名称。这个
功能通过数组名的特定名称搜索
如果它被找到返回的具体名称的索引,-1,如果
它是找不到的。
This function receives an array of strings, called name and anarray of characters that represents a specific name. Thisfunction searches through the array name for the specific nameand returns the index of the specific name if it is found, -1 ifit is not found.
不可能得到阵列格式正确我的歉意。在主我要求用户输入一个名称并将其存储在specificName字符数组中为止。然后在搜索功能我试图搜索名称为用户给定名称的数组,并返回基于如果名称被发现在一定的价值。我已经包括了必要的库文件。我试图做到这一点使用STRCMP,但它似乎并没有正常工作。任何帮助是极大AP preciated!
Couldnt get the arrays to format properly my apologies. In main I ask the user for a name and store it in the specificName char array. Then in the search function I am attempting to search the array of names for the user given name and return a certain value based on if the name is found. I have included the necessary libraries. I am trying to do this using strcmp but it does not seem to work properly. Any help is greatly appreciated!
推荐答案
您可以试试下面的办法:
You could try the following approach:
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int search(char **names,char *specificName, size_t length){
size_t i,found=0;
for(i=0;i<length;i++){
if (strcmp(*(names + i),specificName)==0){
found = 1;
}
}
return found == 1 ? 0 : 1;
}
int main(void) {
size_t length;
char specificName[100];
char *names[12]={"Julias Hoffman","Dianne Conner","Mitchell Cooper","Johnnie Greene",
"Johanna Mason","Kevin Adkins","Brandi Spencer","Marian Tyler",
"Chester Cross","Martin Lawrence","Jane Smith","Sara Jones"};
length = sizeof names / sizeof *(names + 0);
printf("Type a name to be searched:> ");
if( fgets (specificName, 100, stdin) == NULL){
printf("Error!\n");
}
specificName[strcspn(specificName, "\n")] = 0;
if((search(names,specificName,length)) == 0){
printf("Found %s",specificName);
}else{
printf("There was no Record Found.\n");
}
return 0;
}
输出:
Type a name to be searched:> Sara Jones
Found Sara Jones
这篇关于在C字符串的字符数组搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!