Tuesday, 3 November 2009

Creating specialised strings using 'find_first_not_of'

Sometimes we want to create specialised strings that have a particular characteristic. For example a BitString that can only contain '0' and '1'. Or we may want to create a Hex String that can contain '0-9' and 'a-f'. We can also define other specialised types like numeric strings, octal strings, etc. The main thing would be to check to make sure that the string only contains valid characters. We can do this basic check using find_first_not_of function.

Here is a simple program to show its use:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to test specialised strings

#include <iostream>
#include <string>

using namespace
std;

bool
checkIfBitString(string testString)
{

return
(testString.find_first_not_of("01?") == std::string::npos);
}


bool
checkIfHexString(string testString)
{

return
(testString.find_first_not_of("0123456789aAbBcCdDeEfF?") == std::string::npos);
}


int
main()
{

cout<<endl;
string str1("010011000111010101");

if
(checkIfBitString(str1))
cout<<"str1 is a BitString"<<endl;
else

cout<<"str1 is not a BitString"<<endl;

if
(checkIfHexString(str1))
cout<<"str1 can also be a HexString"<<endl;
else

cout<<"str1 is not a HexString"<<endl;

cout<<endl;
string str2("010aBcDeF345678010101");

if
(checkIfBitString(str2))
cout<<"str2 is a BitString"<<endl;
else

cout<<"str2 is not a BitString"<<endl;

if
(checkIfHexString(str2))
cout<<"str2 is a HexString"<<endl;
else

cout<<"str2 is not a HexString"<<endl;

cout<<endl;
string str3("Banana");

if
(checkIfBitString(str3))
cout<<"str3 is a BitString"<<endl;
else

cout<<"str3 is not a BitString"<<endl;

if
(checkIfHexString(str3))
cout<<"str3 is a HexString"<<endl;
else

cout<<"str3 is not a HexString"<<endl;

return
0;
}






The output is as follows:

No comments:

Post a Comment