Re: Array Search?
First of all your declaration of the array is incorrect.
char array[7] declares a character array of 7 characters.
Secondly, it is better to use the C++ class string for storing character
strings.
However if you use a C-alike array in C++ then you can use std::qsort
function to sort your array and then to use binary search for the sorted
array.
Your code will look something like that
#include <cstdlib>
#include <cstring>
int fcmp( const void *a, const void *b )
{
return( std::strcmp( static_cast<const char *>( a ),
static_cast<const char *>( b ) ) );
}
int main( int argc, char *argv[] )
{
std::size_t const array_size = 7;
std::size_t const string_size = 12;
char array[array_size][string_size] = {
"Programming", "Language", "C++", "hello C++", "world", "hello
world", "hello" };
for ( int i = 0; i < array_size; ++i )
std::cout << array[i] << "; ";
std::cout << std::endl;
std::qsort( static_cast<void *>( array ), array_size, string_size,
fcmp );
for ( int i = 0; i < array_size; ++i )
std::cout << array[i] << "; ";
std::cout << std::endl;
char *ptarget = 0; // or char const *ptarget if string should not be
chaged
ptarget = static_cast<char *>( std::bsearch( static_cast<const void
*>( "hello C++" ),
static_cast<const
void *>( array ),
array_size,
string_size, fcmp ) );
if ( ptarget )
std::cout << "The target string is " << ptarget << std::endl;
Vladimri Grigoriev
"Kasya" <kasya_13@hotmail.com> wrote in message
news:FD887E12-E799-47C4-98B3-750E9D675C49@microsoft.com...
Hello,
How can I search Text in Array and find which index is that array in C++?
e.g
char array[7]
array[0] = "Programming";
array[1] = "Language";
array[2] = "C++";
array[3] = "hello C++";
array[4] = "world";
array[5] = "hello world";
array[6] = "hello";
Now how can I find "hello C++" in "array" and find which index is it?
Thanks in Advance!