Home > Enterprise >  c strings: program reads characters following a space as blank spaces
c strings: program reads characters following a space as blank spaces

Time:06-18

after the first space in a space-separated string, the program interprets all characters after the space as blank spaces:

ex:

char test1[] = "hello man";
char test2[128];
    for (int i = 0; i < strlen(test1); i  ){
        if (test1[i] == ' ')
            continue;
        else
            test2[i] = test1[i];
    }
    printf("%s\n", test2);

this program outputs "hello", not "helloman". How do you make it output "helloman"?

CodePudding user response:

You can try adding another counting index that doesn't increment when the character is a space. for example.

int j = 0;  // added this
char test1[] = "hello man";
char test2[128];
for (int i = 0; i < strlen(test1); i  ){
    if (test1[i] == ' ')
        continue;
    else {
        test2[j] = test1[i]; //changes here
        j  ;                 // changes here
    } 
}
test2[j] = 0;                // added this
printf("%s\n", test2);

CodePudding user response:

This happens because test2 is most likely initialized to zero-value bytes (0x0) and because you skip the indices not only in test1 but in test2 as well.

Your memory looks similarly to this before you perform the for loop:

test1
[ 'h', 'e', 'l', 'l', 'o', ' ', 'm', 'a', 'n', 0x0 ]

test2
[ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ... ] # 128 times

Then you copy char after char from test1 to test2 until you hit a space:

test1
[ 'h', 'e', 'l', 'l', 'o', ' ', 'm', 'a', 'n', 0x0 ]

test2
[ 'h', 'e', 'l', 'l', 'o', 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ... ] # 128 times

But then, you want to skip the space, so you continue but the 0x0 character remains in test2 as you move to the next index.

test1
[ 'h', 'e', 'l', 'l', 'o', ' ', 'm', 'a', 'n', 0x0 ]

test2
[ 'h', 'e', 'l', 'l', 'o', 0x0, 'm', 'a', 'n', 0x0, 0x0, 0x0, ... ] # 128 times

As strings are NULL-terminated in C (so the end is marked by the 0x0 byte) it only prints the first part of the string - up until the 0x0 you left in there.

To avoid that you can use a separate index for your test1 and test2 arrays, and increment only the test1 index (the i variable) when the space is found (without incrementing the test2 index):

int test2_index = 0;
char test1[] = "hello man";
char test2[128] = { 0 };
for (int i = 0; i < strlen(test1); i  ){
    if (test1[i] == ' ') {
        continue;
    } else {
        test2[test2_index] = test1[i];
        test2_index  ;
    }
}
printf("%s\n", test2);

You can avoid such errors in the future by using a debugger and inspecting the memory areas of each array after every iteration of the for loop. Alternatively, since you only have 2 arrays and 2 indices and a for loop, you could just step over the algorithm with pen and paper, keeping track of values of every variable after every step.

  • Related