String concatenation without strcat in C

前端 未结 7 761
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 13:44

I am having trouble concatenating strings in C, without strcat library function. Here is my code

#include
#include
#include<         


        
7条回答
  •  有刺的猬
    2021-01-13 14:36

    Old answer below


    You can initialize a string with strcpy, like in your code, or directly when declaring the char array.

    char a1[100] = "Vivek";
    

    Other than that, you can do it char-by-char

    a1[0] = 'V';
    a1[1] = 'i';
    // ...
    a1[4] = 'k';
    a1[5] = '\0';
    

    Or you can write a few lines of code that replace strcpy and make them a function or use directly in your main function.


    Old answer

    You have

            0 1 2 3 4 5 6 7 8 9 ...
        a1 [V|i|v|e|k|0|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_]
        b1 [R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_|_|_|_|_|_]
    

    and you want

            0 1 2 3 4 5 6 7 8 9 ...
        a1 [V|i|v|e|k|R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_]
    

    so ...

    a1[5] = 'R';
    a1[6] = 'a';
    // ...
    a1[12] = 'l';
    a1[13] = '\0';
    

    but with loops and stuff, right? :D

    Try this (remember to add missing bits)

    for (aindex = 5; aindex < 14; aindex++) {
        a1[aindex] = b1[aindex - 5];
    }
    

    Now think about the 5 and 14 in the loop above.

    What can you replace them with? When you answer this, you have solved the programming problem you have :)

提交回复
热议问题