Friday, July 16, 2010

Some string manipulation

Reverse a string
 void ReverseString(char* string) {   if(string == NULL)     return;    int iCharCounter = 0;   for(iCharCounter = 0           ; *(string + iCharCounter) != 0           ; iCharCounter++);    for(int iCharReverse = 0           ; iCharReverse < tempswap ="             *(string">
Make all characters uppercase
 void ToUpper(char* string) {   if(!string)     return;    while(*string)   {     if( ('a' <= *string) && (*string <= 'z') )     {       *string = *string + 'A' - 'a';     }      string++;   }    return; } 
Convert an string of digits to a number(atoi)
 //atoi function: accepts an input string, //extracts all digits from the beginning of //the string and returns the final number int ascii_to_integer(char* string) {   if(!string)     throw std::invalid_argument(       "Null string is not accepted");    int retVal = 0;    if(('0' > *string) || (*string > '9'))     throw std::invalid_argument(       "There must be at least one digit at the beginning of the string");    while( ('0' <= *string) && (*string <= '9') && (*string != 0))   {     retVal = (retVal * 10) + (*string - '0');     string++;   }    return retVal; }  
Print an integer using only putchar
 //Prints an integer using only putchar void print_integer(int value) {   if((value / 10) == 0)   {     putchar('0' + value);   }   else   {     print_integer(value / 10);     putchar('0' + (value % 10));   } }

No comments:

Post a Comment