String Operations - I
posted under
C program
,
C++ program
,
character arrays
,
string operations
,
strings
by Anonymous
A few string operations that are present in other languages but not in C or C++ :-)
#include <cctype>
#include <string>
#include <cstring>
#include <vector>
#include <iostream>
#include <cstdio>
#include <cstdlib>
//Return a lower case version of the given string
std::string toLowerCase( const std::string &s )
{
std::string lower;
for( size_t i = 0; i < s.length(); ++i )
lower.push_back( std::tolower(s[i]) );
return lower;
}
//Return an upper case version of the given string
std::string toUpperCase( const std::string &s )
{
std::string upper;
for( size_t i = 0; i < s.length(); ++i )
upper.push_back( std::toupper(s[i]) );
return upper;
}
//Return the number of occurrences of the given character in the string
int countOf( const std::string &s, char c )
{
size_t count = 0,
sSize = s.length();
for( size_t i = 0; i < sSize; ++i )
if( s[i] == c )
++count;
return count;
}
//Return the number of occurrences of the given string in the main string
int countOf( const std::string &s, const std::string &substr )
{
int count = 0;
size_t i = 0;
while( (i=s.find(substr,i)) != std::string::npos )
++count;
return count;
}
//Return the number of occurrences of the given character in the string
//(Ignores case)
int icountOf( const std::string &s, char c )
{
std::string is = toLowerCase( s );
return countOf( s, std::tolower(c) );
}
//Return the number of occurrences of the given string in the main string
//(Ignores case)
int icountOf( const std::string &s, const std::string &substr )
{
std::string is = toLowerCase( s ),
isubstr = toLowerCase( substr );
return countOf( is, isubstr );
}

Comment Form under post in blogger/blogspot