How can i attach one text array to another text array in c on a given position. For example from input user enters 2 arrays and one digit which is the position.
( _ is empty space )
first: hi my name is ,i learn c
second: Jacob_
pos: 14
result hi my name is jacob ,i learn c
here is my code
#include<stdio.h>
#include<string.h>
#include<ctype.h>
void attach(char *a,char *b,char*c,int pos){
int i,j;
for(i = 0; i < pos;i ){
*(c i) = *(a i);
}
int lenB = strlen(b);
for(i = pos 1;i < lenB;i ){
*(c i) = *(b i);
}
int lenRes = lenB pos;
int lenA = strlen(a);
for(i = lenRes;i < lenA;i ){
*(c i) = *(a i);
}
puts(c);
}
int main()
{
char a[1000],b[1000],c[1000];
gets(a);
gets(b);
int pos;
scanf("%d",&pos);
attach(a,b,c,pos);
return 0;
}
CodePudding user response:
Most of your logic for accessing the strings or doing the loops was just wrong. For example, your second for loop would have zero iterations whenever the user specifies a pos such that pos 1 >= lenB, so that can't be right. You also forgot to add a null termination character at the end of the string.
I kept the basic structure of your program, but cleaned up some minor things and fixed the logic.
#include <stdio.h>
#include <string.h>
void attach(const char * a, const char * b, char * c, int pos) {
int i;
for (i = 0; i < pos; i ) {
c[i] = a[i];
}
int lenB = strlen(b);
for (i = 0; i < lenB; i ) { // I fixed this line
c[pos i] = b[i]; // I fixed this line
}
int lenA = strlen(a);
for (i = pos; i < lenA; i ) { // I fixed this line
c[i lenB] = a[i]; // I fixed this line
}
c[lenA lenB] = 0; // I added this
}
int main()
{
char c[1000];
attach("Hi my name is , I learn C", "David", c, 14);
puts(c); // I moved this to a better place
}
This program produces the output "Hi, my name is David, I learn C".
By the way, c[i] is equivalent to *(c i), so use whichever syntax you find more readable.
Also, to help you find better answers with Internet searches in the future, this operation is not usually called "attach". It is usually called "insert". And we don't call these things "text arrays", we call them "strings". So a better way to ask your question is: "How can I insert a string into the middle of another string?"
