Danny's Tech Musings



String Operations - VI

posted under , , , , by Anonymous


#include <cctype>
#include <string>

#include <cstring>
#include <vector>
#include <iostream>
#include <cstdio>
#include <cstdlib>

//Erase the first occurence of the character in the given string

std::string erase( const char *s, char c )
{
std::string erased;


for( ; *s && *s != c; ++s )
erased.push_back( *s );

for( (*s ? ++s: s); *s; ++s )
erased.push_back( *s );


return erased;

}


//Erase the first occurrence of s2 in s
std::string erase( const char *s, const char *s2 )

{
std::string erased;
const char *skip = NULL;
int s2Len = strlen(s2);


if( (skip = strstr( s, s2 )) )
{
for( ;s != skip; ++s )
erased.push_back( *s );


s += s2Len;
}

for( ; *s; ++s )
erased.push_back( *s );


return erased;
}


//Replace the first occurrence of olds with news in s
std::string replace( const char *s, const char *olds, const char *news )

{
std::string replaced;
const char *skip = NULL;
const char *newsi = NULL;

int oldsLen = strlen(olds);

if( (skip = strstr( s, olds )) )
{
for( ;s != skip; ++s )

replaced.push_back( *s );

for( newsi = news; *newsi; ++newsi )
replaced.push_back( *newsi );

s += oldsLen;

}
for( ; *s; ++s )
replaced.push_back( *s );

return replaced;

}


//Erase all occurrences of the character in the given string
std::string eraseAll( const char *s, char c )
{

std::string erased;

for( ; *s; ++s )
if( *s != c )
erased.push_back( *s );


return erased;

}


//Erase all occurrences of s2 in s
std::string eraseAll( const char *s, const char *s2 )

{
std::string erased;
const char *skip = NULL;
int s2Len = strlen(s2);


while( *s )
{
if( (skip = strstr( s, s2 )) )
{
for( ;s != skip; ++s )

erased.push_back( *s );

s += s2Len;
}
else
{

for( ; *s; ++s )
erased.push_back( *s );
}
}

return erased;

}


//Replace all occurrencs of olds with news in s
std::string replaceAll( const char *s, const char *olds, const char *news )

{
std::string replaced;
const char *skip = NULL;
const char *newsi = NULL;

int oldsLen = strlen(olds);

while( *s )
{
if( (skip = strstr( s, olds )) )

{
for( ;s != skip; ++s )
replaced.push_back( *s );

for( newsi = news; *newsi; ++newsi )
replaced.push_back( *newsi );


s += oldsLen;
}
else
{
for( ; *s; ++s )

replaced.push_back( *s );
}
}

return replaced;
}


0 comments

Make A Comment
top