In real world application we might be handling too many strings. In some cases, we might come across concatenation( gluing two strings ). This tutorial will help you understand the technique without using the strcat() built-in function.
ALGORITHM:
Step #1. Read two string sizes in order to dynamically create the string on the fly.
Step #2. Use mallocĀ function to reserve the necessary memory for the strings
Step #3. The resulting string will have one byte more size than that of the sum of the length of these two strings.
Step #4. Read the strings
Step #5. Now store these strings character by character to the new string.
Step #6. Finally, display the string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
/********************************************************************* * Program to concatenate a string at the end of the another string * * Created By: Dhiraj Jha * * Created Date:9/11/2018 * * *********************************************************************/ #include<stdio.h> #include<conio.h> #include<stdlib.h> int main(){ //declare the necessary variables for dynamically creating string variables char *str1, *str2,*str3; int N1, N2; int i = 0; printf("\nEnter tentative length of the first string: "); scanf("%d", &N1); //DMA str1 = (char *)malloc(N1*sizeof(char)); printf("\nEnter tentative length of the second string: "); scanf("%d", &N2); //DMA str2 = (char *)malloc(N2*sizeof(char)); str3 = (char *)malloc((N1+N2+1)*sizeof(char)); printf("Enter the string #1"); scanf("%s", str1); printf("\nEnter the string #2"); scanf("%s", str2); while(*str1 != '\0'){ *(str3+i) = *str1; // the value of the pointer stored str1++; i=i+1; } //for blank space *(str3+i) = ' ';//to store 1 blank space between two string, at the last position while(*str2 != '\0'){ i = i+1; //change the pointer to the next character *(str3+i) = *str2; str2++; } *(str3+i+1) = '\0';// finally end the string with the NULL character printf("\nThe new string is %s", str3);//print the value of the final string //don't forget to free the memory reserved during DMA using free() function free(str1); free(str2); free(str3); getch(); return 0; }//main ends |
[Note: This algorithm can be improved in so many ways. I highly recommend to comment if found so. ]
Count Vowels, consonants or numbers in a given string.
Leave a Reply
You must be logged in to post a comment.