EonTea
EonTea

Reputation: 13

Concatenating substring?

i would like to find out how i could concatenate substrings.

For Example, if i was given the word xyz i would like my output to be xxyxyz

I have tried writing my code using Strncat , basically i have would like to extract substrings and concatenate it into the output.

How do i 'pull out' substrings from a string generated from user input and be able to input it into string format for C?

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

int main()
{
char str[100];
int i;

printf("Enter Word :" );
scanf("%s",str);

for(i=0;i<strlength(str);i++){
strncat(str(i),str(i++),i++)
}

printf("conc : %s" , str);

return 0;

}

Upvotes: 1

Views: 133

Answers (2)

Prakash
Prakash

Reputation: 110

we can concatenate substring in different ways

one way is like you with small modifications(by allocating memory dynamically and other way using arrays)

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

int main()
{
    char *str;
    int i, len;

    str = (char *) malloc(100);
    printf("Enter word: ");
    scanf("%s", str);

    len = strlen(str);

    for (i = 1; i <= len; i++)
    {
        strncat(str, str, i);
    }

    strcpy(str,str+len);
    printf("conc: %s\n", str);

return 0;
} // main

or

int main()
{
    char str[100]           ={0};
    char ResultString[100]  ={0};
    int i, len;

    printf("Enter word: ");
    scanf("%s", str);

    len = strlen(str);

    for (i = 1; i <= len; i++)
    {
        strncat(ResultString, str, i);
    } 

    printf("conc: %s\n", ResultString);

return 0;
} // main

Upvotes: 0

Barmar
Barmar

Reputation: 780974

You need a separate variable for the result string, instead of concatenating to the same string you're starting with. Initialize it to an empty string, then use strncat to concatenate the substrings to it.

To get a substring, use strncpy().

char input[100];
char output[5000] = "";
size_t i;

printf("Enter word: ");
scanf("%s", input);

size_t len = strlen(input);

for (i = 0; i < len; i++) {
    strncat(output, input, i);
}

printf("conc: %s\n", output);

Upvotes: 2

Related Questions