- C Programming Tutorial
- C - Home
- Basics of C
- C - Introduction
- C - Features
- C - Basics
- C - History
- C - Structure of C Program
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Tokens
- C - Keywords
- C - Identifiers
- C - User Input
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Integer Promotions
- C - Type Conversion
- C - Type Casting
- C - Booleans
- Constants and Literals in C
- C - Constants
- C - Literals
- C - Escape sequences
- C - Format Specifiers
- Operators in C
- C - Operators
- C - Arithmetic Operators
- C - Relational Operators
- C - Logical Operators
- C - Bitwise Operators
- C - Assignment Operators
- C - Unary Operators
- C - Increment and Decrement Operators
- C - Ternary Operator
- C - sizeof Operator
- C - Operator Precedence
- C - Misc Operators
- Decision Making in C
- C - Decision Making
- C - if statement
- C - if...else statement
- C - nested if statements
- C - switch statement
- C - nested switch statements
- Loops in C
- C - Loops
- C - While loop
- C - For loop
- C - Do...while loop
- C - Nested loop
- C - Infinite loop
- C - Break Statement
- C - Continue Statement
- C - goto Statement
- Functions in C
- C - Functions
- C - Main Function
- C - Function call by Value
- C - Function call by reference
- C - Nested Functions
- C - Variadic Functions
- C - User-Defined Functions
- C - Callback Function
- C - Return Statement
- C - Recursion
- Scope Rules in C
- C - Scope Rules
- C - Static Variables
- C - Global Variables
- Arrays in C
- C - Arrays
- C - Properties of Array
- C - Multi-Dimensional Arrays
- C - Passing Arrays to Function
- C - Return Array from Function
- C - Variable Length Arrays
- Pointers in C
- C - Pointers
- C - Pointers and Arrays
- C - Applications of Pointers
- C - Pointer Arithmetics
- C - Array of Pointers
- C - Pointer to Pointer
- C - Passing Pointers to Functions
- C - Return Pointer from Functions
- C - Function Pointers
- C - Pointer to an Array
- C - Pointers to Structures
- C - Chain of Pointers
- C - Pointer vs Array
- C - Character Pointers and Functions
- C - NULL Pointer
- C - void Pointer
- C - Dangling Pointers
- C - Dereference Pointer
- C - Near, Far and Huge Pointers
- C - Initialization of Pointer Arrays
- C - Pointers vs. Multi-dimensional Arrays
- Strings in C
- C - Strings
- C - Array of Strings
- C - Special Characters
- C Structures and Unions
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Self-Referential Structures
- C - Lookup Tables
- C - Dot (.) Operator
- C - Enumeration (or enum)
- C - Structure Padding and Packing
- C - Nested Structures
- C - Anonymous Structure and Union
- C - Unions
- C - Bit Fields
- C - Typedef
- File Handling in C
- C - Input & Output
- C - File I/O (File Handling)
- C Preprocessors
- C - Preprocessors
- C - Pragmas
- C - Preprocessor Operators
- C - Macros
- C - Header Files
- Memory Management in C
- C - Memory Management
- C - Memory Address
- C - Storage Classes
- Miscellaneous Topics
- C - Error Handling
- C - Variable Arguments
- C - Command Execution
- C - Math Functions
- C - String Functions
- C - Static Keyword
- C - Random Number Generation
- C - Command Line Arguments
C Programming - C Strings
![]() Share with a Friend |
C Programming - C Strings
C Strings
In C, strings are arrays of characters that are terminated by a null character ('\0'). They are used to store and manipulate text data.
- Declaring and Initializing Strings
Declaration:
Strings in C are declared as character arrays:
C
char str[20]; // Can hold up to 19 characters and 1 null character
Initialization:
There are two main ways to initialize a string:
- Character Array:
C
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
- String Literal:
C
char str[] = "Hello";
- Accessing String Characters
Individual characters in a string can be accessed using array indexing:
C
char str[] = "Hello";
printf("%c", str[0]); // Output: H
- Input and Output of Strings
Reading a String:
Using scanf():
C
char name[50];
printf("Enter your name: ");
scanf("%s", name); // Reads input until a space or newline
- Limitation: scanf() cannot read strings with spaces. For that, use gets() (deprecated) or fgets().
Output a String:
Using printf():
C
char str[] = "Hello, World!";
printf("%s", str);
- Common String Functions
C provides a library <string.h> with many functions for string manipulation.
(a) String Length:
To find the length of a string:
C
#include <string.h>
char str[] = "Hello";
int len = strlen(str); // Returns 5
(b) String Copy:
To copy one string into another:
C
#include <string.h>
char src[] = "Hello";
char dest[10];
strcpy(dest, src); // Copies "Hello" into dest
(c) String Concatenation:
To concatenate (join) two strings:
C
#include <string.h>
char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2); // str1 becomes "Hello, World!"
(d) String Comparison:
To compare two strings:
C
#include <string.h>
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2); // Returns 0 if equal, <0 if str1 < str2, >0 if str1 > str2
(e) Substring Search:
To find a substring within a string:
C
#include <string.h>
char str[] = "Hello, World!";
char *substr = strstr(str, "World"); // Returns pointer to "World"
(f) Character Search:
To find a character in a string:
C
#include <string.h>
char str[] = "Hello";
char *ch = strchr(str, 'e'); // Returns pointer to 'e'
- String Operations Without Library Functions
C programmers can implement string operations manually using loops.
(a) String Length:
C
int string_length(char str[]) {
int i = 0;
while (str[i] != '\0') {
i++;
}
return i;
}
(b) String Copy:
C
void string_copy(char dest[], char src[]) {
int i = 0;
while (src[i] != '\0') {
dest[i] = src[i];
i++;
}
dest[i] = '\0'; // Null-terminate the destination string
}
(c) String Concatenation:
C
void string_concatenate(char str1[], char str2[]) {
int i = 0, j = 0;
while (str1[i] != '\0') {
i++;
}
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0';
}
- Dynamic String Allocation
Strings can be dynamically allocated using malloc() or calloc().
Example:
C
#include <stdio.h>
#include <stdlib.h>
int main() {
char *str = (char *)malloc(20 * sizeof(char)); // Allocate memory for 20 characters
if (str == NULL) {
printf("Memory allocation failed!");
return 1;
}
strcpy(str, "Hello, Dynamic!");
printf("%s\n", str);
free(str); // Free allocated memory
return 0;
}
- Common Mistakes with Strings
- Uninitialized Strings:
C
char str[10];
printf("%s", str); // Undefined behavior
- Buffer Overflow:
C
char str[5];
strcpy(str, "Hello, World!"); // Exceeds allocated memory
- Forgetting the Null Character:
C
char str[5] = {'H', 'e', 'l', 'l', 'o'}; // No null character, not a proper string
- Advantages of Strings in C
- Simple and lightweight.
- Direct access to individual characters.
- Extensive library support in <string.h>.
- Limitations of Strings in C
- Fixed-size character arrays limit flexibility.
- Manual memory management can lead to errors like buffer overflow or memory leaks.
- No built-in string data type, unlike modern languages.
- Example Program
C
#include <stdio.h>
#include <string.h>
int main() {
char name[50];
char greeting[100] = "Hello, ";
printf("Enter your name: ");
scanf("%s", name);
strcat(greeting, name); // Concatenate name to greeting
strcat(greeting, "! Welcome to C programming.");
printf("%s\n", greeting); // Display final greeting
return 0;
}
Output:
Enter your name: Alice
Hello, Alice! Welcome to C programming.
