Strings in C and C++: char Arrays vs std::string
Join, compare and search text in both languages, and see why std::string saves you from buffer overflows.
- Length, joining and comparing strings
- strcat, strcmp and strstr in C
- size(), +=, == and find() in C++
char s[32]
- strlen(s)
- strcat(s, " Lovelace")
- strcmp(a, b) == 0
- you manage the size
std::string s
- s.size()
- s += " Lovelace"
- a == b
- grows automatically
Two ways to store text
The problem
Joining a first and last name, comparing passwords, searching for a word: text is everywhere. In C, text is a raw array you must manage yourself, and mistakes overflow memory. C++ offers std::string, which handles that for you.
Think of it like this
A C string is like writing on a fixed-size notepad: if the text is longer than the page, it spills onto the desk. A std::string is like a document in a word processor: it grows as you type and always knows its own length.
char name[32]📒 A notepad with 32 squaresstrcat(name, " Lovelace")✍️ Add text; it must still fitname += " Lovelace";📄 C++: the document grows by itselfstrcmp("cat", "cat") == 0🔍 Compare contents, not addressesIn C a string is a null-terminated char array handled with functions such as strlen and strcat, while C++ std::string is an object that owns and grows its text automatically.
Important points
char name[32]reserves room sostrcatcan append " Lovelace" safely.strcmpreturns 0 when two C strings have the same characters.strstrreturns a pointer to the found text or NULL;findreturnsstd::string::nposwhen missing.std::transformwithstd::touppermakes an uppercase copy;substr(0, 3)extracts"Ada".
When to use it
- Building, comparing and searching text such as names, commands and messages.
- Converting C strings at the boundary with C libraries.
- Processing input line by line.
When not to use it
- Unicode text where one visible character can be several bytes: use a Unicode-aware library.
- Raw char arrays in new C++ code without a strong reason: prefer
std::string.
C and C++ code examples
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
/* A C string is a char array that ends with '\0'. */
char name[32] = "Ada";
printf("%s has %zu letters\n", name, strlen(name));
/* strcat appends; the array must have room for the result. */
strcat(name, " Lovelace");
printf("%s\n", name);
/* strcmp returns 0 when two strings are equal. */
printf("equal: %d\n", strcmp("cat", "cat") == 0);
/* Walk the characters until the terminating '\0'. */
char upper[32];
size_t i = 0;
for (; name[i] != '\0'; i++) {
upper[i] = (char)toupper((unsigned char)name[i]);
}
upper[i] = '\0';
printf("%s\n", upper);
/* strstr finds a substring and returns a pointer to it, or NULL. */
printf("contains \"love\": %s\n", strstr("lovelace", "love") ? "yes" : "no");
return 0;
}
Ada has 3 letters
Ada Lovelace
equal: 1
ADA LOVELACE
contains "love": yes
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
int main() {
// std::string manages its own memory and grows as needed.
std::string name = "Ada";
std::cout << name << " has " << name.size() << " letters\n";
name += " Lovelace";
std::cout << name << '\n';
// == compares the contents of two strings.
std::cout << "equal: " << (std::string("cat") == "cat") << '\n';
std::string upper = name;
std::transform(upper.begin(), upper.end(), upper.begin(),
[](unsigned char c) { return static_cast<char>(std::toupper(c)); });
std::cout << upper << '\n';
// find returns std::string::npos when the text is missing.
std::string word = "lovelace";
std::cout << "contains \"love\": " << (word.find("love") != std::string::npos ? "yes" : "no") << '\n';
std::cout << "first name: " << name.substr(0, 3) << '\n';
}
Ada has 3 letters
Ada Lovelace
equal: 1
ADA LOVELACE
contains "love": yes
first name: Ada
C and C++ comparison
In C, strlen, strcat, strcmp and strstr work on raw arrays, and you must make sure the array is large enough. std::string offers size(), +=, ==, find() and substr() and grows automatically, which avoids buffer overflows.
C exposes small procedural APIs and makes representation details explicit.
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.
String functions in C and C++
char name[] = "Ada"; | C: a string is a char array ending with the null character '\0' |
strlen(name) | C: length, not counting '\0' (needs <string.h>) |
strcpy(dest, src) | C: copy a string (dest must be big enough) |
strcat(dest, src) | C: append src to the end of dest |
strcmp(a, b) == 0 | C: true when the strings are equal |
strchr(s, 'a'), strstr(s, "ab") | C: find a character or a substring |
snprintf(buf, sizeof buf, "%s=%d", key, n) | C: build a string safely, never past the buffer size |
std::string name = "Ada"; | C++: a string that manages its own memory (needs <string>) |
name.size(), name + "!", a == b | C++: length, joining and comparing |
name.substr(0, 2), name.find("da") | C++: part of a string, and the position of a substring |
std::to_string(42), std::stoi("42") | C++: number to string, and string to number |
std::getline(std::cin, line) | C++: read a whole line, including spaces |
Common mistakes with strings in C and C++
Comparing C strings with ==
In C, == compares the addresses of the two arrays, not their characters. Use strcmp().
char a[] = "cat";
char b[] = "cat";
if (a == b) puts("equal"); /* never printed */
char a[] = "cat";
char b[] = "cat";
if (strcmp(a, b) == 0) puts("equal");
No room for the terminating '\0'
A C string needs one extra char for '\0'. Without it, functions like strlen and printf read past the end.
char word[5];
strcpy(word, "hello"); /* 5 letters + '\0' = 6 bytes */
char word[6];
strcpy(word, "hello");
Assigning to a char array with =
Arrays cannot be assigned in C. Copy with strcpy, or use std::string in C++.
char name[10];
name = "Ada"; /* error */
char name[10];
strcpy(name, "Ada");
Reading a line with std::cin >>
cin >> stops at the first space, so only the first word is read. Use std::getline for a whole line.
std::string full_name;
std::cin >> full_name; // "Ada Lovelace" gives "Ada"
std::string full_name;
std::getline(std::cin, full_name);
Not checking find() against npos
When the substring is missing, find() returns std::string::npos, a very large number, not -1 or 0.
std::string s = "hello";
std::cout << s.substr(s.find("z")); // throws std::out_of_range
std::string s = "hello";
auto pos = s.find("z");
if (pos != std::string::npos) std::cout << s.substr(pos);
Frequently asked questions
What is the difference between a char array and std::string?
A char array is a fixed block of characters ending with '\0', and you manage its size yourself. std::string, in C++ only, grows as needed and supports +, == and many helper methods, so it is safer for most code.
How do I get the length of a string in C?
Call strlen(s) from <string.h>. It counts the characters before '\0', so the array must be at least strlen(s) + 1 bytes long. In C++, use s.size().
How do I compare two strings in C?
Use strcmp(a, b): it returns 0 when they are equal, a negative number when a comes first and a positive number when b comes first.
How do I convert a number to a string?
In C, use snprintf(buf, sizeof buf, "%d", n). In C++, use std::to_string(n), and std::stoi or std::stod to convert back.
How do I read a string with spaces?
In C, use fgets(buf, sizeof buf, stdin), which keeps the newline. In C++, use std::getline(std::cin, line).
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Count Uppercase Letters Count the capital letters in a text. Easy
- Initials From a Name Build uppercase initials from a full name. Easy
- Replace Spaces With Dashes Turn spaces into dashes to make a URL-style slug. Easy