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;
}


String Operations - V

posted under , , , , by Anonymous



#include <cctype>
#include <string>

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

//Remove leading white space

std::string leftTrim( const std::string &s )
{
std::string trimmed;

size_t i;
for( i = 0; i < s.length() && isblank(s[i]); ++i ); //Skip white space


for( ; i < s.length(); ++i )
trimmed.push_back( s[i] );

return trimmed;

}

//Remove trailing white space
std::string rightTrim( const std::string &s )
{
std::string trimmed;
size_t length = s.length(),

i,
j;

for( i = length-1; i >= 0 && isblank(s[i]); --i );


for( j = 0; j <= i; ++j )
trimmed.push_back( s[j] );

return trimmed;

}

//Remove leading and trailing white space
std::string trim( const std::string &s )
{
std::string trimmed;
size_t length = s.length(),

i,
j,
k;

for( i = 0; i < length && isblank(s[i]); ++i ); //Left trim


for( k = length-1; k >= 0 && isblank(s[k]); --k ); //Right trim



for( j = i; j <= k; ++j )
trimmed.push_back( s[j] );

return trimmed;
}


String Operations - IV

posted under , , , , by Anonymous



#include <cctype>
#include <string>

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

std::string toString( bool value )

{
return value?"true":"false";
}

std::string toString( int value )

{
char buffer[ 256 ];
sprintf( buffer, "%d", value );
return buffer;

}

std::string toString( double value )
{
char buffer[ 256 ];

sprintf( buffer, "%lf", value );
return buffer;
}

std::string toString( char value )

{
char buffer[ 2 ];
buffer[0] = value;
buffer[1] = '\0';


return buffer;
}


String Operations III

posted under , , , , by Anonymous



#include <cctype>
#include <string>

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


int readInt( const std::string &s )
{
int value;
std::sscanf( s.c_str(), "%d", &value );

return value;
}

double readDouble( const std::string &s )
{

double value;
std::sscanf( s.c_str(), "%lf", &value );
return value;
}

char readChar( const std::string &s )
{
char value;
std::sscanf( s.c_str(), "%c", &value );

return value;
}

bool readBool( const std::string &s )
{

bool value;
return s == "true";
}

String Operations II

posted under , , , , by Anonymous


#include <cctype>
#include <string>

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

//Returns whether the given string starts with the specified string

bool startsWith( const std::string &s, const std::string &start )
{
size_t sSize = s.length(),

startSize = start.length();

bool starts = sSize >= startSize;

if( starts )

for( size_t i = 0; i < startSize; ++i )
if( start[i] != s[i] )
{
starts = false;

break;
}

return starts;

}


//Returns whether the given string ends with the specified string
bool endsWith( const std::string &s, const std::string &end )
{

size_t sSize = s.length(),
endSize = end.length();

bool ends = sSize >= endSize;

if( ends )

{
for( size_t i = endSize-1; i >= 0; --i )
if( end[i] != s[i] )
{

ends = false;
break;
}
}


return ends;
}

//Returns whether the given string starts with the specified string
//(Ignores case)
bool istartsWith( const std::string &s, const std::string &start )

{
size_t sSize = s.length(),
startSize = start.length();

bool starts = sSize >= startSize;


if( starts )
for( size_t i = 0; i < startSize; ++i )
if( tolower(start[i]) != tolower(s[i]) )
{

starts = false;
break;
}

return starts;


}


//Returns whether the given string starts with the specified string
//(Ignores case)
bool iendsWith( const std::string &s, const std::string &end )

{
size_t sSize = s.length(),
endSize = end.length();

bool ends = sSize >= endSize;


if( ends )
{
for( size_t i = endSize-1; i >= 0; --i )
if( tolower(end[i]) != tolower(s[i]) )

{
ends = false;
break;
}
}


return ends;
}

String Operations - I

posted under , , , , 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 );
}


Boosting Priority Of A Process

posted under , , , , , , by Anonymous

Sometimes it is necessary to increase the priority of a particular process in order to get better response or performance. This can be done using the command line using the "nice" command. To do the same thing and also control how a process its scheduled and its priority, the following program may be used. You need to have root access to perform these operations.

You can get the system values for the minimum and maximum priorities using the following functions:

int sched_get_priority_min( int ALGORITHM );
int sched_get_priority_max( int ALGORITHM );

ALGORITHM may be

  • SCHED_RR (Round Robin)
  • SCHED_FIFO(First In, First Out Queue Type Algorithm where the process is pre-empted only during an I/O operation)
  • SCHED_OTHER(Default Linux Scheduling Algorithm)
  • SCHED_BATCH(Batch scheduling)




#include <sched.h>

bool boostPriority( int pid, int priority )

{
bool boosted = true;

//Declare structure for storing scheduling information
sched_param p;


//Get the current scheduling information
//A value of 0 denotes the current process
//Otherwise, the process with the given pid is denoted
sched_getparam( pid, &p );


//This is the parameter we are interested in for changing the priority
//It is always best to get the current scheduling parameters, change
//the value of sched_priority and use the same sstructure to set
//the new priority
p.sched_priority = priority;


//Set the priority. Returns non-zero value if error occurs
if( sched_setparam( pid, &p) )
boosted = false;



return boosted;
}


glob Example

glob is a wonderful utility which retrieves the list of files from a specified location and returns the files which match the given regular expression.

The glob_t structure is used to store the result of the globbing operation. The globfree function is used to free the memory allocated for the structure after globbing.

The number of matches is stored in gl_pathc (Glob Path Count) field of glob_t.
Each match is stored in gl_pathv (Glob Path Value) field of glob_t.

I think its better to check if gl_pathc is greater than zero before invoking globfree, as otherwise it caused a segmentation fault on my system.

Type "man glob" at the console without the quotes to get a lot of detailed information.



#include <glob.h>
#include <string>

#include <vector>
using namespace std;

void getFiles( const string &pattern, vector<string> &fileList )

{
//Declare glob_t for storing the results of globbing
glob_t globbuf;

//Glob.. GLOB_TILDE tells the globber to expand "~" in the pattern to the home directory
glob( pattern.c_str(), GLOB_TILDE, NULL, &globbuf);

for( int i = 0; i < globbuf.gl_pathc; ++i )
fileList.push_back( globbuf.gl_pathv[i] );

//Free the globbuf structure

if( globbuf.gl_pathc > 0 )
globfree( &globbuf );

}


Find MAC/Network Hardware Address On Linux/Unix

The following piece of code will help you find the MAC(Media Access Control)/Hardware Address of your network card. An important point is that Linux sometimes sets up virtual addresses and these addresses are retrieved as well. You can also get the names of your network interfaces/cards on your system.




#include <sys/ioctl.h>
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <cstdio>
using namespace std;

void getMAC( )
{
//Interface structure to pass commands to ioctl
struct ifreq ifr;


//Structure containing the network interface name and index
struct if_nameindex* if_name;

//Convenience variable to point to the MAC address
unsigned char* mac;

//String buffer to store the MAC
char actualMac[ 50 ];

int sd,
i = 0;

sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
if(sd != -1)
{

//Retrieve the available list of network interface cards and their names and indices
if_name = if_nameindex();

//Parse the list
//The ending entry in if_name is terminated by NULL
while( if_name[i].if_name != NULL )

{
//Copy the interface name to the ioctl request structure
memcpy(&ifr.ifr_name, if_name[i].if_name, IFNAMSIZ);

//Pass signal to ioctl requesting the hardware address
if (ioctl(sd, SIOCGIFHWADDR, &ifr) >= 0)
{
//Assign result in MAC (because "mac" is shorter than "ifr.ifr_hwaddr.sa_data" :-D )
mac = (unsigned char*) &ifr.ifr_hwaddr.sa_data;

//Store the address as a string in "actualMac"

sprintf(actualMac,"%02X:%02X:%02X:%02X:%02X:%02X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);

}
else //Error: Unable to retrieve the address
printf("Unable to retrieve MAC address for %s\n", if_name[i].if_name );


++i;
}

//Free the buffers used by the if_nameindex function
if_freenameindex(if_name);
}

}



top