Definition:
- In C, a string is an array of characters.
- Strings in C are null-terminated, meaning they are followed by a null character (
'\0'
) to mark the end.
Declaration:
- Strings can be declared using the character array syntax.
char myString[10]; // Declares a character array to store a string of up to 9 characters.
Initialization:
- Strings can be initialized at the time of declaration.
char str2[] = "Hello"; // Initializes str2 with "Hello" string literals
char str3[10] = {'H', 'i', '\0'}; // Initializes str3 with "Hi" char array
String Input and Output:
- To input a string,
scanf
orgets
can be used.
scanf("%s", myString);
gets(myString); // Be cautious, as gets() may lead to buffer overflow.
- To output a string,
printf
orputs
can be used.
printf("String: %s\n", myString);
puts(myString);
Traversing String
Traversing string is somewhat different from the traversing an integer array. We need to know the length of the array to traverse an integer array, whereas we may use the null character in the case of string to identify the end the string and terminate the loop.
Hence, there are two ways to traverse a string.
- By using the length of string
- By using the null character.
Using the length of string
example of counting the number of vowels in a string.
#include<stdio.h>
void main ()
{
char s[] = "thecodepathshala";
int i = 0;
int count = 0;
while(i<strlen(s))
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels %d",count);
}
/*
Output:
The number of vowels 6
*/
Using the null character
same example of counting the number of vowels by using the null character.
#include<stdio.h>
void main ()
{
char s[] = "thecodepathshala";
int i = 0;
int count = 0;
while(s[i] != NULL)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
//printf("%d-%c\n",i,s[i]);
count ++;
}
i++;
}
printf("The number of vowels %d",count);
}
/*
Output:
The number of vowels 6
*/
Pointers with strings:
pointers can be used to point to the strings. There are various advantages of using pointers to point strings. Let us consider the following example to access the string via the pointer.
#include<stdio.h>
void main ()
{
char s[11] = "thecodepathshala";
char *p = s; // pointer p is pointing to the first character of string s.
printf("%s",p); // the string thecodepathshala is printed if we print p.
}
/*
Output:
thecodepathshala
*/
Pointer Arithmetic with Strings:
- Pointers can be used to traverse through the characters of a string.
char greeting[] = "Hello";
char *ptr = greeting;
while (*ptr != '\0') {
printf("%c", *ptr);
ptr++;
}
Functions for String Manipulation:
- Standard string functions in
<string.h>
can be used for various string operations. - Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[20];
// Copying one string to another
strcpy(str2, str1);
// Concatenating two strings
strcat(str2, " World");
// Finding the length of a string
int length = strlen(str2);
printf("Concatenated String: %s\n", str2);
printf("Length of the String: %d\n", length);
return 0;
}
Pointers and String Functions:
- Pointers can be used in conjunction with string functions for efficient manipulation.
- Example:
char str[] = "Programming";
char *ptr = str;
// Using strchr to find the first occurrence of a character
char *found = strchr(ptr, 'g');
if (found != NULL) {
printf("Found at index: %ld\n", found - ptr);
}
Dynamic Memory Allocation for Strings:
- Pointers are often used for dynamic memory allocation when working with strings of unknown size.
char *dynamicString = (char*)malloc(50 * sizeof(char));
Example:
#include <stdio.h>
int main() {
char greeting[] = "Hello";
char *ptr = greeting;
while (*ptr != '\0') {
printf("%c", *ptr);
ptr++;
}
return 0;
}
String Functions
C provides several string manipulation functions in the <string.h>
library:
strlen(str)
: Returns the length of the stringstr
.strcpy(dest, src)
: Copies the stringsrc
todest
.strcat(dest, src)
: Concatenatessrc
to the end ofdest
.strcmp(str1, str2)
: Compares two strings lexicographically.strchr(str, ch)
: Returns a pointer to the first occurrence of characterch
instr
.strstr(str1, str2)
: Returns a pointer to the first occurrence ofstr2
instr1
.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[20];
// Finding the length of a string
printf("Length of str1: %d\n", strlen(str1));
// Copying a string
strcpy(str2, str1);
printf("Copied string: %s\n", str2);
// Concatenating strings
strcat(str2, " World");
printf("Concatenated string: %s\n", str2);
// Comparing strings
if (strcmp(str1, str2) == 0)
printf("Strings are equal\n");
else
printf("Strings are not equal\n");
// Finding a character in a string
char *ptr = strchr(str2, 'W');
if (ptr != NULL)
printf("Found 'W' at position: %ld\n", ptr - str2);
else
printf("'W' not found\n");
return 0;
}
String Manipulation:
- Characters in a string can be accessed using array notation.
char ch = myString[2]; // Accesses the character at index 2.
- Strings can be modified directly using array notation or with string functions.
Important Note:
- Ensure that strings have enough space to accommodate the characters and the null terminator.
- Be cautious about buffer overflows, and use functions like
fgets
orscanf
with field width specifier to limit input size.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char greeting[] = "Hello";
printf("Length of the string: %lu\n", strlen(greeting));
return 0;
}