0% found this document useful (0 votes)
8 views

Unit 3 String Excercise 3

Uploaded by

tv5874
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit 3 String Excercise 3

Uploaded by

tv5874
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 10

School of Computing Science and Engineering

Course Code : R1UC101B Name: Programming for Problem Solving-C

UNIT III
String: Exercise:-3

Program Name: B.Tech. (CSE)


Ex-1 : C Program to Concatenate Two Strings

In this example, you will learn to concatenate two strings manually without
using the strcat() function.
As you know, the best way to concatenate two strings in C programming is
by using the strcat() function. However, in this example, we will
concatenate two strings manually.

#include <stdio.h>
int main() {
char s1[100] = "programming ", s2[] = "is awesome";
int length, j;
Continue…

// store length of s1 in the length variable


length = 0;
while (s1[length] != '\0') {
++length;
}

// concatenate s2 to s1
for (j = 0; s2[j] != '\0'; ++j, ++length) {
s1[length] = s2[j];
}
Continue…

// terminating the s1 string


s1[length] = '\0';

printf("After concatenation: ");


puts(s1);

return 0;
}
Output
After concatenation: programming is awesome

Here, two strings s1 and s2 and concatenated and the result is stored
in s1.

It's important to note that the length of s1 should be sufficient to


hold the string after concatenation. If not, you may get unexpected
output.
Ex-2: C Program to Copy String Without Using strcpy()

In this example, you will learn to copy strings without using the strcpy()
function.
As you know, the best way to copy a string is by using the strcpy()
function. However, in this example, we will copy a string manually
without using the strcpy() function.

#include <stdio.h>
int main() {
char s1[100], s2[100], i;
printf("Enter string s1: ");
fgets(s1, sizeof(s1), stdin);

for (i = 0; s1[i] != '\0'; ++i) {


s2[i] = s1[i];
}
Ex-2: C Program to Copy String Without Using strcpy()

s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}
Output
Length of the string: 18
References

 http://kirste.userpage.fu-berlin.de/chemnet/use/info/libc/libc_7.html
 Let Us C by Yashavant Kanetkar : Authentic Guide to C PROGRAMMING Language 17th
Edition, BPB Publications
 C in Depth by by S.K.Srivastava and Deepali Srivastava, BPB Publications

You might also like