Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Tuesday, December 8, 2009

Integer to String

 String intToStr( int num ){
    int i = 0;
    boolean isNeg = false;
    /* Buffer big enough for largest int and - sign */
    char[] temp = new char[ MAX_DIGITS + 1 ];

    /* Check to see if the number is negative */
    if( num < 0 ){
        num *= -1;
        isNeg = true;
    }

    /* Fill buffer with digit characters in reverse order */
    do {
        temp[i++] = (char)((num % 10) + '0');
        num /= 10;
    } while( num != 0 );

    StringBuffer b = new StringBuffer();
    if( isNeg )
        b.append( '-' );

    while( i > 0 ){
        b.append( temp[--i] );
    }

    return b.toString();
}

String to Integer

int strToInt( string str ){
    int i = 0, num = 0;
    bool isNeg = false;
    int len = str.Length();

    if( str[0] == '-' ){
        isNeg = true;
        i = 1;
    }

    while( i < len ){
        num *= 10;
        num += ( str[i++] - '0' );
    }

    if( isNeg )
        num *= -1;

    return num;
}

Reverse Words

/*
Function that reverses the order of the words in a string. For example, function should transform the string “Do or do not, there is no try.” to “try. no is there not, do or Do”.
*/
void reverseWords( char str[] )
{
    int start = 0, end = 0, length;

    length = strlen(str);
    /* Reverse entire string */
    reverseString(str, start, length - 1);

    while( end < length )
    {
       if( str[end] != ' ' )
       { /* Skip non-word characters */

           /* Save position of beginning of word */
           start = end;

           /* Scan to next non-word character */
           while( end < length && str[end] != ' ' )
               end++;
            /* Back up to end of word */
            end--;

            /* Reverse word */
            reverseString( str, start, end );
        }
        end++; /* Advance to next token */
    }
}

void reverseString( char str[], int start, int end )
{
    char temp;
    while( end > start )
    {
        /* Exchange characters */
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;

        /* Move indices towards middle */
        start++; end--;
    }
}