i want to locate a string of characters from an array of characters. the string i want to locate is stored in a variable. the code is in C. any help. if theres a function like array.indexof in CPP or any way i could go abt it. thanks
example, u have characters ‘Kenya’ stored in char array country. U have a bigger char array called world where u have elements as the countries in the world and u want to locate kenya and if possible return u the index of kenya in array world
You have to search using a graph algorithm
you will need to create your own function for that using strstr or strchr, C does not have a direct implementaton for what you are trying to do ( size_t find (const string& str, size_t pos = 0) const )
try something similar to below
char * long_sring = "i want to locate a string of characters from an array of characters. the string i want to locate is stored in a variable";
char* search = strstr(long_string "string");
if(search != null)
int index_of_substring = long_string - search; // this will give you the index of "string"
am getting invalid operand to binary, bcoz the long_string and search are char n u r trying to assign them to int variable.
earlier post was demo purposes only and was never prove read, use the following, tested and it works
char* long_string = "i want to locate a string of characters from an array of characters. the string i want to locate is stored in a variable";
char* search = strstr(long_string, "string"); // will get you the first instance of "string"
//above line (search) will return "string of characters from an array of characters. the string i want to locate is stored in a variable"
int index_of_substring=0; // define int
if(search != NULL )
{
//since we have the length on both long_string and search, subtract the lengths (strlen) and you have a zero based index
index_of_substring = strlen(long_string) - strlen(search); // this will give you the index of "string"
//above line returns 19
}
I found a way of searching and returning the index of the value searched. I used the strcmp() function. My problem now is am using a loop. Wen the loop runs i get the first index of the first variable am searching bt doesnt give the index of the second.
This helped alot. Thanks
I now have the first variable and its index returned
recursive loop is your answer