1: String Basics
In C, a string is a sequence of characters stored in an array terminated by a null character (' '
). Strings are represented using character arrays (char[]
) and are widely used for text manipulation.
-
String Declaration:
char str[] = "Hello"; // String declaration and initialization
-
String Initialization:
char greeting[20] = "Hello, World!"; // Array size includes space for null terminator
-
Accessing Characters in a String:
char ch = str[0]; // Accessing the first character ('H')
2: String Manipulation Functions
C provides several built-in functions in the <string.h>
library for manipulating strings.
- Example String Functions:
#include <string.h>
char str1[20] = "Hello";
char str2[] = "World";// Concatenating strings
strcat(str1, " ");
strcat(str1, str2); // Result: "Hello World"// Getting string length
int len = strlen(str1); // Result: 11 (excluding null terminator)// Comparing strings
int result = strcmp(str1, str2); // Result: -1 (based on lexicographical order)
3: String Input/Output
Strings can be input from the user using the scanf()
function and output using the printf()
function.
-
Reading a String from User:
char name[50];
printf("Enter your name: ");
scanf("%s", name); // Reads a string (stops at whitespace)
-
Printing a String:
printf("Hello, %s!n", name); // Outputs "Hello, [name]!"
4: Practice and Examples
- Practice Exercise:
- Write a program that reads a string from the user and prints its length.
- Implement a function to count the number of vowels in a given string.
- Develop a program to reverse a string.
#include <stdio.h>
#include <string.h>
// Function to count the number of vowels in a string
int countVowels(const char *str) {
int count = 0;
for (int i = 0; str[i] != ' '; i++) {
char ch = tolower(str[i]); // Convert character to lowercase for case-insensitive comparison
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++;
}
}
return count;
}
// Function to reverse a string
void reverseString(char *str) {
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
char temp = str[i];
str[i] = str[length - 1 - i];
str[length - 1 - i] = temp;
}
}
int main() {
char input[100];
printf("Enter a string: ");
scanf("%s", input);
// Print string length
printf("Length of the string: %ldn", strlen(input));
// Count vowels in the string
printf("Number of vowels: %dn", countVowels(input));
// Reverse the string
reverseString(input);
printf("Reversed string: %sn", input);
return 0;
}
Understanding strings and their manipulation functions is essential for handling textual data in C programming. Practice using string functions to perform common operations such as concatenation, comparison, input/output, and transformation. Strengthening your skills with string manipulation will enable you to work effectively with text-based applications and algorithms.