简体   繁体   中英

Garbage values; strange string strlen value

I am trying to write a function that inserts one string into another string at a specified value. It is returning a few garbage values toward the end of the new string, presumably because, for some reason, the strlen of the new string is greater than what it should be; strlen(combo) should equal s1 + s2 but it does not. I am not sure why it is returning 13 instead of 9 as the length. Here's my code:

#include <stdio.h>
#include <string.h>

void insertString(char *string1, char *string2, int position) {
    int i, j = 0, k = 0, s1 = strlen(string1), s2 = strlen(string2);
    char combo[s1 + s2];

    for (i = 0; i < s1 + s2; i++) {
        combo[i] = i;
    }

    for (i = 0; i < s1 + s2; i++) {
        if (i < position) {
            combo[i] = string1[i];
            j++;
        }
        else if (i >= position && i < position + s2) {
            combo[i] = string2[k];
            k++;
        }
        else if (i >= position + s2) {
            combo[i] = string1[j];
            j++;
        }
    }
    for (i = 0; i < strlen(combo); i++){
        printf("%c", combo[i]);
    }

    printf ("\n comboLength = %lu\n", strlen(combo));
    printf ("s1 = %d\n", s1);
    printf ("s2 = %d\n", s2);
}


int main (void) {
    insertString("I pie", "like", 2);

    return 0;
}

EDIT: Added the null character. Still returning a single garbage value several spaces to the right of the new string, and still not returning 9 as the proper string length.

#include <stdio.h>
#include <string.h>

void insertString(char *string1, char *string2, int position) {
    int i, j = 0, k = 0, s1 = strlen(string1), s2 = strlen(string2);
    char combo[s1 + s2];

    for (i = 0; i <= s1 + s2; i++) {
        combo[i] = i;
    }

    for (i = 0; i < s1 + s2; i++) {
        if (i == s1 + s2) {
            combo[i] = '\0';
        }
        else if (i < position) {
            combo[i] = string1[i];
            j++;
        }
        else if (i >= position && i < position + s2) {
            combo[i] = string2[k];
            k++;
        }
        else if (i >= position + s2) {
            combo[i] = string1[j];
            j++;
        }
    }
    for (i = 0; i < strlen(combo); i++){
        printf("%c", combo[i]);
    }

    printf ("\n comboLength = %lu\n", strlen(combo));
    printf ("s1 = %d\n", s1);
    printf ("s2 = %d\n", s2);
}


int main (void) {
    insertString("I pie", "like", 2);

    return 0;
}

You are lacking a terminating \\0 in your combo string. strlen() returns the length excluding the terminating null-byte.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM