suppose there are two strings str1 and str2.
suppose i filled str1 with some characters.Now what i want to do is copying string str2 at some specified location in str1.
How can i do it?

Recommended Answers

All 7 Replies

what code do you use? C? .Net?

How can i do it?

Depends. Do you want to overwrite the characters or do you want to insert the characters and shift everything down..

i don't want to overwrite the characters.
i want to append the characters at the end.

Do you mean something like this?

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

int main(int argc, char**argv)
{
    /*make sure str1 is padded with enough room*/
    char str1[] = {'H','e','l','l','o',',',' ','W','o','r','l','d','\0',' ',' ', ' ', ' ', ' ', ' '};
    char str2[] = "this is more text";

    fprintf(stdout, "str1->%s\n", str1);
    fprintf(stdout, "str2->%s\n", str2);

    /*append text*/

    strcat(str1, &str2[12]);

    fprintf(stdout, "str1->%s\n", str1);

    exit(EXIT_SUCCESS);
}

To append to strings in C you use strcat. To copy from another string you use strcpy. (There are variants of these that allow you to specify a length - check your documentation).

It is unclear to me which you need. Below is an example that shows how to use both.

int main () {
    char str1[32] = {};
    char str2[32] = {};

    /* Place data in str1 */
    strcpy (str1, "abcdefghijklmnopqrstuvwxyz");

    /* Copy from within str1 to str2 */
    strcpy (str2, str1 + 5);

    printf ("str1 : %s\n", str1);
    printf ("str2 : %s\n", str2);

    /* clear strings */
    memset (str1, 0, 32);
    memset (str2, 0, 32);

    /* Place data in str1 */
    strcpy (str1, "12345");

    /* Place data in str2 */
    strcpy (str2, "09876");

    /* Append str2 to the end of str1 */
    strcat (str1, str2);

    printf ("str1 : %s\n", str1);

    return 0;
}
With reference to ur query,
int main()
{
char str1[50];
char str2[50];
int n;
clrscr();
printf("Enter str1");
scanf("%s",&str1);
puts(str1);
printf("Enter str2");
scanf("%s",&str2);
puts(str2);
printf("Enter location in digits");
scanf("%d",&n);
strcpy(str1+n,str2);
puts(str1);
getch();
return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.