UNIT-IV
String Processing
Introduction to String Processing:
- Strings are sequences of characters widely used in programming.
- String processing involves manipulating and analyzing strings.
Standard String Library Functions:
- `strlen(str)`: Returns the length of the string.
- `strcpy(dest, src)`: Copies the content of the source string to the destination.
- `strcat(str1, str2)`: Concatenates two strings.
- `strcmp(str1, str2)`: Compares two strings.
- Examples of usage for each function.
1. String Length (strlen):
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "Hello, World!";
int length = strlen(str);
printf("Length of the string: %d\n", length);
return 0;
}
2. String Copy (strcpy):
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[20];
strcpy(destination, source);
printf("Copied string: %s\n", destination);
return 0;
}
3. String Concatenation (strcat):
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
4. String Comparison (strcmp):
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
if (strcmp(str1, str2) == 0) {
printf("Strings are equal\n");
} else {
printf("Strings are not equal\n");
}
return 0;
}
5. Substring Extraction (strncpy):
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[10];
strncpy(destination, source, 5);
destination[5] = '\0'; // Ensure null-termination for printing as a string
printf("Substring: %s\n", destination);
return 0;
}
1. Introduction to Files in C:
File:
A file is a collection of data stored on a storage medium.
Two main types: text files (human-readable) and binary files (machine-readable).
File Handling:
The <stdio.h> header in C provides functions for file handling.