Practice Questions — Strings - C-style and std::string
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output?
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[] = "Hello";
cout << strlen(s) << endl;
cout << sizeof(s) << endl;
return 0;
}strlen counts characters before \0. sizeof counts total bytes including \0.
56Question 2
Easy
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello";
cout << s.length() << endl;
cout << s[1] << endl;
return 0;
}length() returns character count. Indexing is 0-based.
5eQuestion 3
Easy
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string a = "Hello";
string b = " World";
string c = a + b;
cout << c << endl;
return 0;
}The + operator concatenates strings.
Hello WorldQuestion 4
Medium
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello, World!";
cout << s.substr(7, 5) << endl;
return 0;
}substr(start_pos, length) extracts a substring.
WorldQuestion 5
Medium
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "abcdefgh";
size_t pos = s.find("cde");
cout << pos << endl;
pos = s.find("xyz");
cout << (pos == string::npos ? "Not found" : "Found") << endl;
return 0;
}find returns the starting index, or string::npos if not found.
2Not foundQuestion 6
Medium
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello";
s.insert(5, " World");
cout << s << endl;
s.erase(5, 6);
cout << s << endl;
return 0;
}insert adds at position. erase removes from position.
Hello WorldHelloQuestion 7
Medium
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
int n = 42;
string s = "Value: " + to_string(n);
cout << s << endl;
string num = "123";
cout << stoi(num) + 7 << endl;
return 0;
}to_string converts number to string. stoi converts string to int.
Value: 42130Question 8
Hard
What is the output?
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s1[] = "hello";
char s2[] = "hello";
if (s1 == s2) cout << "Equal" << endl;
else cout << "Not equal" << endl;
if (strcmp(s1, s2) == 0) cout << "Content equal" << endl;
return 0;
}== compares addresses for C-strings. strcmp compares content.
Not equalContent equalQuestion 9
Easy
What is the difference between
strlen(s) and sizeof(s) for the C-string char s[] = "Hello";?One counts characters, the other counts bytes.
strlen(s) returns 5 -- the number of characters before the null terminator. sizeof(s) returns 6 -- the total size of the array including the null terminator '\0'. strlen is O(n) (scans until '\0'). sizeof is a compile-time constant.Question 10
Medium
What is
string::npos and when is it returned?It is the return value of find() when the substring is not found.
string::npos is a constant of type size_t with the maximum possible value (typically 18446744073709551615 on 64-bit). It is returned by find(), rfind(), and similar functions when the search string is not found. Always compare with string::npos, not with -1.Question 11
Hard
What is the output?
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s = "abcba";
string rev = s;
reverse(rev.begin(), rev.end());
cout << (s == rev ? "Palindrome" : "Not") << endl;
return 0;
}Reverse the string and compare with the original.
PalindromeQuestion 12
Hard
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello World";
s.replace(s.find("World"), 5, "C++");
cout << s << endl;
cout << s.length() << endl;
return 0;
}find returns 6. replace(6, 5, "C++") replaces 5 chars with 3 chars.
Hello C++9Question 13
Medium
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string a = "apple";
string b = "banana";
cout << (a < b) << endl;
cout << (a > b) << endl;
cout << (a == "apple") << endl;
return 0;
}String comparison is lexicographic (dictionary order).
101Question 14
Hard
Why is the frequency array approach O(n) for anagram checking while the sorting approach is O(n log n)?
Think about what each approach does.
The frequency array approach iterates through each string once (O(n) each) and then checks 26 counts (O(1)). Total: O(n). The sorting approach sorts both strings (O(n log n) each) and then compares them (O(n)). Total: O(n log n). The frequency array is faster but only works for lowercase letters. For Unicode, sorting may be simpler.
Question 15
Easy
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello";
s += " World";
s.append("!");
cout << s << endl;
return 0;
}+= and append both concatenate to the end.
Hello World!Question 16
Medium
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "HELLO";
for (char &c : s) {
c = c + 32;
}
cout << s << endl;
return 0;
}Adding 32 to an uppercase ASCII letter gives the lowercase version.
helloQuestion 17
Hard
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "aababcabc";
int count = 0;
size_t pos = 0;
while ((pos = s.find("ab", pos)) != string::npos) {
count++;
pos++; // Move past this match
}
cout << count << endl;
return 0;
}Count all occurrences of "ab" including overlapping ones.
3Question 18
Easy
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello";
s[0] = 'J';
cout << s << endl;
return 0;
}std::string characters can be modified by index.
JelloQuestion 19
Medium
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "12345";
int sum = 0;
for (char c : s) {
sum += c - '0';
}
cout << sum << endl;
return 0;
}c - '0' converts a digit character to its integer value.
15Question 20
Hard
Why is
strcpy considered dangerous and what is the alternative?Think about what happens when the source is longer than the destination.
strcpy copies characters until it finds '\0' with no bounds checking. If the source is longer than the destination buffer, it writes past the buffer boundary (buffer overflow). Alternatives: strncpy (copies at most n characters), or better yet, use std::string which manages memory automatically.Mixed & Application Questions
Question 1
Easy
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello";
cout << s[0] << s[4] << endl;
return 0;
}s[0] is the first character, s[4] is the last.
HoQuestion 2
Easy
What is the output?
#include <iostream>
#include <cstring>
using namespace std;
int main() {
cout << strcmp("abc", "abc") << endl;
cout << strcmp("abc", "abd") << endl;
cout << strcmp("abd", "abc") << endl;
return 0;
}strcmp returns 0, negative, or positive.
0-11Question 3
Medium
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello World";
int count = 0;
for (char c : s) {
if (c == 'l') count++;
}
cout << count << endl;
return 0;
}Count how many 'l' characters are in "Hello World".
3Question 4
Easy
Write a program that reads a string and prints it reversed without using any library reverse function.
Use a loop from the last index to 0.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s);
for (int i = s.length() - 1; i >= 0; i--) {
cout << s[i];
}
cout << endl;
return 0;
}
Input: Hello
Output: olleHQuestion 5
Medium
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "123";
int n = stoi(s);
n *= 2;
s = to_string(n);
cout << s << endl;
return 0;
}Convert to int, double it, convert back to string.
246Question 6
Medium
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "abcdef";
s.erase(2, 3); // Remove 3 chars starting at index 2
cout << s << endl;
cout << s.length() << endl;
return 0;
}erase(2, 3) removes characters at indices 2, 3, 4.
abf3Question 7
Medium
Write a function that checks if a given string is a palindrome (ignoring case).
Convert to lowercase first, then use two-pointer comparison.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
bool isPalindrome(string s) {
for (char &c : s) c = tolower(c);
int l = 0, r = s.length() - 1;
while (l < r) {
if (s[l] != s[r]) return false;
l++; r--;
}
return true;
}
int main() {
cout << isPalindrome("Racecar") << endl; // 1
cout << isPalindrome("Hello") << endl; // 0
cout << isPalindrome("Madam") << endl; // 1
return 0;
}Question 8
Hard
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "aaabbbccc";
int freq[26] = {0};
for (char c : s) freq[c - 'a']++;
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
cout << (char)('a' + i) << ":" << freq[i] << " ";
}
}
cout << endl;
return 0;
}Build a frequency array and print characters with non-zero counts.
a:3 b:3 c:3Question 9
Hard
Write a function that takes two strings and checks if they are anagrams using a frequency array.
Increment for string 1, decrement for string 2. All counts should be 0.
#include <iostream>
#include <string>
using namespace std;
bool isAnagram(string a, string b) {
if (a.length() != b.length()) return false;
int freq[26] = {0};
for (char c : a) freq[c - 'a']++;
for (char c : b) freq[c - 'a']--;
for (int i = 0; i < 26; i++)
if (freq[i] != 0) return false;
return true;
}
int main() {
cout << isAnagram("listen", "silent") << endl; // 1
cout << isAnagram("hello", "world") << endl; // 0
return 0;
}Question 10
Hard
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "the quick brown fox";
int words = 1;
for (char c : s) {
if (c == ' ') words++;
}
cout << words << endl;
return 0;
}Count spaces + 1 = number of words (assuming single spaces, no leading/trailing spaces).
4Question 11
Medium
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "C++ Programming";
cout << s.substr(0, 3) << endl;
cout << s.substr(4) << endl;
return 0;
}substr(0, 3) gets first 3 chars. substr(4) gets from index 4 to end.
C++ProgrammingQuestion 12
Easy
What is the output?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello";
cout << s.empty() << endl;
s = "";
cout << s.empty() << endl;
return 0;
}empty() returns true (1) if the string has 0 characters.
01Multiple Choice Questions
MCQ 1
Which header is needed for
strlen, strcpy, strcmp?Answer: B
B is correct.
B is correct.
<cstring> provides C-string functions: strlen, strcpy, strcat, strcmp. <string> provides the std::string class.MCQ 2
What is the null terminator character in C-strings?
Answer: C
C is correct.
C is correct.
'\0' (ASCII 0) marks the end of a C-string. '0' is the digit zero (ASCII 48). '\n' is newline.MCQ 3
What does
s.length() return for string s = "Hello";?Answer: B
B is correct.
B is correct.
length() returns the number of characters in the string: 5 for "Hello". Unlike C-strings, std::string does not count any null terminator in its length.MCQ 4
How do you concatenate two
std::string objects?Answer: C
C is correct.
C is correct.
std::string overloads the + and += operators for concatenation. strcat is for C-strings only. There is no concat or add method.MCQ 5
What does
strcmp return when two strings are equal?Answer: C
C is correct.
C is correct.
strcmp returns 0 when strings are equal, a negative value when the first is less, and a positive value when the first is greater.MCQ 6
What does
string::find return when the substring is not found?Answer: C
C is correct.
C is correct.
find returns string::npos (the maximum size_t value) when the substring is not found. Comparing with -1 works but string::npos is the correct idiom.MCQ 7
What is the time complexity of
strlen()?Answer: B
B is correct.
B is correct.
strlen scans from the beginning until it finds '\0', making it O(n). In contrast, std::string::length() is O(1) because the length is stored internally.MCQ 8
What does
stoi("42abc") return?Answer: B
B is correct.
B is correct.
stoi reads as many characters as possible that form a valid integer: "42". The remaining "abc" is ignored. It returns 42. It would throw invalid_argument only if the string starts with a non-numeric character.MCQ 9
Which approach is faster for anagram checking: sorting or frequency array?
Answer: C
C is correct. The frequency array approach iterates each string once: O(n). Sorting both strings is O(n log n). The frequency array is faster for lowercase-only strings (fixed 26-element array).
C is correct. The frequency array approach iterates each string once: O(n). Sorting both strings is O(n log n). The frequency array is faster for lowercase-only strings (fixed 26-element array).
MCQ 10
What does
char* s = "Hello"; vs char s[] = "Hello"; differ in?Answer: B
B is correct.
B is correct.
char* s = "Hello" makes s point to a string literal in read-only memory (modifying it is undefined behavior). char s[] = "Hello" creates a writable copy in local memory.MCQ 11
What is the output of
cout << string("abc") + string("def");?Answer: B
B is correct. The
B is correct. The
+ operator for std::string concatenates without any separator. "abc" + "def" = "abcdef".MCQ 12
What does
c_str() return?Answer: C
C is correct.
C is correct.
c_str() returns a const char* pointing to a null-terminated C-string representation of the std::string. It is used when C APIs require a char*.MCQ 13
What is the output of
string s = "abc"; cout << s + "def";?Answer: A
A is correct. The
A is correct. The
+ operator concatenates std::string with a C-string literal. "abc" + "def" = "abcdef" with no separator.MCQ 14
What does
s.substr(3) return if s = "HelloWorld"?Answer: B
B is correct.
B is correct.
substr(3) with one argument returns everything from index 3 to the end. For "HelloWorld", characters from index 3 onward are "loWorld".MCQ 15
What does
stoi("abc") do?Answer: C
C is correct.
C is correct.
stoi throws std::invalid_argument when the string does not start with a valid integer representation. "abc" has no leading digits.MCQ 16
What is the correct way to read a full line of text including spaces?
Answer: B
B is correct.
B is correct.
getline(cin, s) reads the entire line including spaces. cin >> s stops at the first whitespace character.MCQ 17
Which is more efficient for checking string equality: sorting both then comparing, or using a frequency array?
Answer: C
C is correct. Building a frequency array takes O(n). Sorting takes O(n log n). For anagram checking with lowercase letters, the frequency approach is asymptotically faster.
C is correct. Building a frequency array takes O(n). Sorting takes O(n log n). For anagram checking with lowercase letters, the frequency approach is asymptotically faster.
MCQ 18
What does
to_string(3.14) return?Answer: B
B is correct.
B is correct.
to_string for floating-point numbers uses a default format with 6 decimal places, producing something like "3.140000". For controlled formatting, use stringstream with setprecision.Coding Challenges
Challenge 1: Count Vowels and Consonants
EasyRead a string (may contain spaces) and count the number of vowels (a, e, i, o, u -- case-insensitive) and consonants. Ignore non-alphabetic characters.
Sample Input
Hello World
Sample Output
Vowels: 3
Consonants: 7
Use tolower() or char arithmetic for case conversion. Use isalpha() to filter.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string s;
getline(cin, s);
int vowels = 0, consonants = 0;
for (char c : s) {
c = tolower(c);
if (isalpha(c)) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
vowels++;
else
consonants++;
}
}
cout << "Vowels: " << vowels << endl;
cout << "Consonants: " << consonants << endl;
return 0;
}Challenge 2: First Non-Repeating Character
MediumGiven a string, find the first character that does not repeat. Print the character and its index. If all characters repeat, print 'None'.
Sample Input
aabbcdd
Sample Output
First non-repeating: c at index 4
Use a frequency array. Single pass to count, second pass to find first with count 1.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s);
int freq[256] = {0};
for (char c : s) freq[(int)c]++;
for (int i = 0; i < (int)s.length(); i++) {
if (freq[(int)s[i]] == 1) {
cout << "First non-repeating: " << s[i] << " at index " << i << endl;
return 0;
}
}
cout << "None" << endl;
return 0;
}Challenge 3: Remove All Occurrences of a Character
MediumRead a string and a character. Remove all occurrences of that character from the string. Print the resulting string and its length.
Sample Input
programming
m
Sample Output
Result: prograing
Length: 9
Use erase and find in a loop, or build a new string. Do NOT use any external library.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
char ch;
getline(cin, s);
cin >> ch;
string result = "";
for (char c : s) {
if (c != ch) result += c;
}
cout << "Result: " << result << endl;
cout << "Length: " << result.length() << endl;
return 0;
}Challenge 4: Word Reverser
HardRead a sentence and reverse the order of words. Do not reverse individual characters within words. Example: 'hello world' becomes 'world hello'.
Sample Input
I love competitive programming
Sample Output
programming competitive love I
Handle multiple spaces between words. Use string operations.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string s;
getline(cin, s);
vector<string> words;
string word = "";
for (int i = 0; i <= (int)s.length(); i++) {
if (i == (int)s.length() || s[i] == ' ') {
if (!word.empty()) {
words.push_back(word);
word = "";
}
} else {
word += s[i];
}
}
for (int i = words.size() - 1; i >= 0; i--) {
cout << words[i];
if (i > 0) cout << " ";
}
cout << endl;
return 0;
}Challenge 5: Longest Palindromic Substring (Brute Force)
HardGiven a string, find and print the longest substring that is a palindrome. If there are multiple of the same length, print the first one found.
Sample Input
babad
Sample Output
bab
O(n^3) brute force is acceptable. Check all substrings and verify palindrome.
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string s) {
int l = 0, r = s.length() - 1;
while (l < r) {
if (s[l] != s[r]) return false;
l++; r--;
}
return true;
}
int main() {
string s;
cin >> s;
string longest = "";
for (int i = 0; i < (int)s.length(); i++) {
for (int len = 1; len <= (int)s.length() - i; len++) {
string sub = s.substr(i, len);
if (isPalindrome(sub) && (int)sub.length() > (int)longest.length()) {
longest = sub;
}
}
}
cout << longest << endl;
return 0;
}Challenge 6: String Compression (Run-Length Encoding)
HardImplement basic string compression using run-length encoding. Consecutive duplicate characters are replaced with the character followed by the count. If the compressed string is not shorter, return the original.
Sample Input
aabcccccaaa
Sample Output
a2b1c5a3
Single pass. Handle edge cases: empty string, single character, no repeats.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s;
if (s.empty()) {
cout << s << endl;
return 0;
}
string compressed = "";
int count = 1;
for (int i = 1; i <= (int)s.length(); i++) {
if (i < (int)s.length() && s[i] == s[i - 1]) {
count++;
} else {
compressed += s[i - 1];
compressed += to_string(count);
count = 1;
}
}
if ((int)compressed.length() >= (int)s.length()) {
cout << s << endl;
} else {
cout << compressed << endl;
}
return 0;
}Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn C++ with a live mentor?
Explore our C++ Masterclass