unit-2 c&ds
unit-2 c&ds
C String Initialization
In C programming, gets() and puts() are functions used for handling strings.
gets()
Purpose: Reads a line of text from standard input (usually the keyboard) and stores
it in a string.
Usage: gets(char *str);
Example:
char str[100];
gets(str);
printf("You entered: %s\n", str);
.
puts()
To use them, you must include the <string.h> header file in your program:
#include <string.h>
1)String Length:To get the length of a string, you can use
the strlen() function:
#include <string.h>
int main() {
printf("%d", strlen(alphabet));
return 0;
}
Output:
26
sizeof will always return the memory size (in bytes), and
not the actual string length:
example:
#include <stdio.h>
#include <string.h>
int main() {
return 0;
Output:
Size is: 50
2)Concatenate Strings:
To concatenate (combine) two strings, you can use
the strcat() function:
Example:
#include <stdio.h>
#include <string.h>
int main() {
strcat(str1, str2);
// Print str1
printf("%s", str1);
return 0;
3)Copy Strings
To copy the value of one string to another, you can use
the strcpy() function:
#include <stdio.h>
#include <string.h>
int main() {
strcpy(str2, str1);
// Print str2
printf("%s", str2);
return 0;
4)Compare Strings
To compare two strings, you can use the strcmp() function.
It returns 0 if the two strings are equal, otherwise a value that is not 0:
#include <stdio.h>
#include <string.h>
int main() {
return 0;
Output:
-4