Reputation: 109
How do I implement a c++ script to search a group of characters from an character array.The search characters are not case sensitive.For an example, I key in "aBc" and the character array has "abcdef" and it is a hit and shows the found.
This is my script,don't know what is wrong.
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main()
{
char charArr1[]="abcdefghi";
char inputArr[20];
cin>>inputArr;
charArr1.find("abc");
}
I recevied this error. request for member 'find' in 'charArr1', which is of non-class type 'char [10]
Upvotes: 0
Views: 6379
Reputation: 153909
The easiest solution is to convert the input to lower case, and
use std::search
:
struct ToLower
{
bool operator()( char ch ) const
{
return ::tolower( static_cast<unsigned char>( ch ) );
}
};
std::string reference( "abcdefghi" );
std::string toSearch;
std::cin >> toSearch;
std::transform( toSearch.begin(), toSearch.end(), toSearch.begin(), ToLower() );
std::string::iterator results
= std::search( reference.begin(), reference.end(),
toSearch.begin(), toSearch.end() );
if ( results != reference.end() ) {
// found
} else {
// not found
}
The ToLower
class should be in your toolkit; if you do any
text processing, you'll use it a lot. You'll notice the type
conversion; this is necessary to avoid undefined behavior due to
the somewhat special interface of ::tolower
. (Depending on
the type of text processing you do, you may want to change it to
use the ctype
facet in std::locale
. You'd also avoid the
funny cast, but the class itself will have to carry some excess
bagage to keep a pointer to the facet, and to keep it alive.)
Upvotes: 1
Reputation: 3559
Upvotes: 3