Skip to content

Strings

In C, a string is a sequence of characters stored in contiguous memory, terminated by a special null character ('\0'). Unlike modern languages (like Python or Java) that have a built-in string type, C uses character arrays to represent strings.

char str[] = "Hello";
IndexValue
0H
1e
2l
3l
4o
5\0
  • Every string in C must end with '\0'.
  • Stored in contiguous memory.
  • Terminated with null character.
  • Can be manipulated using <string.h> library functions.
  • Must allocate enough space for all characters plus one for '\0'.
char str[] = "Hello";
  • Compiler adds '\0' automatically.
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char str[20] = "Hello"; // extra space available
  • Always allocate an extra byte for ‘\0’.
char name[20];
scanf("%s", name); // stops at space
printf("Name: %s", name);
gets(name);
fgets(name, sizeof(name), stdin);
  • Reads full line, including spaces.
  • Safer than gets().
name[strcspn(name, "\n")] = '\0';
printf("%s", str);
puts(str); //adds newline automatically.
  • Pointer points to string literal in read-only memory.
  • Modifying this is undefined behavior.
FunctionDescription
strlen(s)Length of string (without '\0').
strcpy(dest, src)Copy string.
strncpy()Copy up to n characters.
strcat()Append one string to another.
strcmp(s1, s2)Compare two strings.
strchr()Find first occurrence of a character.
strstr()Find substring.
  • Always include:
#include <string.h>
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "C Programming";
printf("Length: %zu", strlen(str));
return 0;
}
char src[] = "Hello";
char dest[20];
strcpy(dest, src);
char str1[20] = "Hello ";
char str2[] = "World";
strcat(str1, str2);
if(strcmp("abc", "abc") == 0)
printf("Equal");
int my_strlen(char *str) {
int length = 0;
while(str[length] != '\0')
length++;
return length;
}
AspectString LiteralCharacter Array
MutabilityCannot modify (read-only)Can modify
StorageStored in text segmentStored in stack or heap
Null RequiredYesYes
  • Efficient representation of text.
  • Wide library support.
  • Manual memory management.
  • Risk of buffer overflow if not careful.
  • Text processing (editors, compilers).
  • File paths handling.
  • Command-line argument parsing.
  • Network protocols (message parsing).
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[100];
int count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for(int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
count++;
}
printf("Vowel count: %d\n", count);
return 0;
}