0

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]

1
  • 1
    Is there any reason why you don't use std::string? This would be a lot easier. Commented Jul 19, 2013 at 14:40

2 Answers 2

3
  1. copy your inputs and convert them to lower case (see How to convert std::string to lower case?)
  2. perform usual search (http://www.cplusplus.com/reference/string/string/find/)
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry for the spam, I am new here. Thanks for the reply!
The answer in the link you post is incorrect, and invokes undefined behavior (at least on many platforms). You cannot call ::tolower with a char.
1

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.