Direct String Manipulation

As programmer, you have a choice: You can manipulate information as it’s sent to output or you can manipulate it in memory and then send the result to output. Depending on what the program does, however, you may not have that luxury. Sometimes you must make modifications in memory, saving them for later.

In last week’s Lesson, I demonstrated how spaces can be changed to newlines when a string is sent to output. This week’s Lesson shows you the same thing, but with the string manipulated first, then sent to output. Either way, the object of the game is the same: Hunt down a space and change it to a newline. Here’s the code:

#include <stdio.h>

int main()
{
    char ob1[] = "These are not the droids you're looking for.\n";
    int x;

    x = 0;
    while(ob1[x])
    {
        if(ob1[x] == ' ')
            ob1[x] = '\n';
        x++;
    }
    puts(ob1);

    return(0);
}

This example is actually a tad bit simpler than the example from last week’s Lesson.

The while loop starting at Line 9 plows through the string ob1. In the loop, if the character ob1[x] is a space, it’s replaced with a newline (Lines 11 and 12). Otherwise, the value of x is incremented to continue working through the string.

The puts() function at Line 15 displays the modified results.

To perform the same action in the same way by using pointers, you’d need to make a few modifications. Primarily, you lose the integer variable x, which acts like an index, and replace it with a char pointer x, which can directly march through the string:

#include <stdio.h>>

int main()
{
    char ob1[] = "These are not the droids you're looking for.\n";
    char *x;

    x = ob1;
    while(*x)
    {
        if(*x == ' ')
            *x = '\n';
        x++;
    }
    puts(ob1);

    return(0);
}

Pointer x is initialized at Line 8. The while loop works pretty much the same, although pointer x is manipulated directly instead of using an offset into the ob1 array (something like *(x+1)).

Either way the puzzle is solved, the results are the same: The string is modified in memory, space characters changed to newlines. The string is then output all at once.

Leave a Reply