C-Style Strings

Character arrays and string functions

Interview Relevant: Legacy code understanding

C-Style Strings

Null-terminated character arrays from C.

Code Examples

C-style strings and common operations.

cpp
1#include <cstring>
2
3// C-string declaration
4char str1[] = "Hello";  // Size 6 (includes null terminator)
5char str2[10] = "World";
6
7// String functions from <cstring>
8int len = strlen(str1);           // 5
9strcpy(str2, str1);               // Copy str1 to str2
10strcat(str1, str2);               // Concatenate (careful with buffer!)
11int cmp = strcmp(str1, str2);     // Compare: 0 if equal
12char* found = strstr(str1, "ll"); // Find substring
13
14// Safe alternatives
15strncpy(str2, str1, 9);  // Copy at most 9 chars
16strncat(str2, str1, 5);  // Append at most 5 chars
17
18// Prefer std::string in modern C++!

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In