Strings are crucial in C programming, acting as character arrays terminated by \backslash. Mastering string manipulation is essential for handling input, files, and data parsing.
This collection of 30 C programming string exercises is designed to sharpen your skills across all difficulty levels, from Beginner to Advanced.
Each exercise includes a Problem Statement, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely understand how and why it works.
What You’ll Practice
These challenges focus on mastering:
- Fundamentals: String declaration, I/O, and the use of core library functions like
strlen(),strcpy(),strcat(), andstrcmp(). - Manipulation: Custom logic for reversing strings, checking for palindromes, finding substrings, and counting characters.
- Pointers & Arrays: Understanding the
charpointer relationship and using pointer arithmetic for efficient string traversal. - Advanced: Case conversion, string formatting, and tokenization.
Use Online C Compiler to solve exercises.
+ Table of Contents (30 Exercises)
Table of contents
- Exercise 1: Read and Print String
- Exercise 2: String Length
- Exercise 3: Copy String
- Exercise 4: Concatenate Strings
- Exercise 5: Compare Strings
- Exercise 6: Convert to Uppercase
- Exercise 7: Convert to Lowercase
- Exercise 8: Toggle Case
- Exercise 9: Vowels and Consonants
- Exercise 10: Words in a String
- Exercise 11: Specific Character Count
- Exercise 12: First Occurrence
- Exercise 13: Last Occurrence
- Exercise 14: Character Frequency
- Exercise 15: Remove Specific Character
- Exercise 16: Non-Repeating Character
- Exercise 17: Remove Extra Spaces
- Exercise 18: Check For Digit
- Exercise 19: Extract Substring
- Exercise 20: Search Substring
- Exercise 21: Reverse String
- Exercise 22: Palindrome Check
- Exercise 23: Reverse Words
- Exercise 24: Remove Duplicates
- Exercise 25: Check Anagrams
- Exercise 26: Sort String
- Exercise 27: Highest Frequency Character
- Exercise 28: String to Integer (atoi)
- Exercise 29: Integer to String (itoa)
- Exercise 30: URL Parser (Simple)
Exercise 1: Read and Print String
Problem Statement: Write a C program to prompt the user to enter a string (which may contain spaces) and then print the exact string back to the console.
Expected Output:
Enter a string (up to 99 characters):
PYnative
You entered: PYnative
+ Hint
The standard scanf("%s", ...) stops reading at the first whitespace. To read a line including spaces, use the fgets() function, specifying the buffer, the maximum size, and the input stream (stdin).
+ Show Solution
#include <stdio.h>
int main() {
// Declare a character array (string) with a suitable size
char str[100];
printf("Enter a string (up to 99 characters):\n");
// Use fgets to read the entire line, including spaces
// 100 is the max size, stdin is the input stream
fgets(str, 100, stdin);
printf("You entered: %s", str);
return 0;
}Code language: C++ (cpp)
Explanation:
- A character array (
char str[100];) is declared to hold the string. - The
fgets(str, 100, stdin)function is used for input because it reliably reads a full line of text, including spaces, until it encounters a newline character (\n) or the maximum size (100 in this case) is reached. - It automatically includes the newline character in the string (if the buffer wasn’t full). The final
printf()simply outputs the content of thestrarray using the%sformat specifier.
Exercise 2: String Length
Problem Statement: Calculate and print the length of a string without using the built-in strlen() function.
Given:
char str[] = "Hello World!";Code language: C++ (cpp)
Expected Output:
The string is: "Hello World!"
The length of the string is: 12
+ Hint
All C-style strings are terminated by a null character (\0). Start a counter at 0 and iterate through the string array character by character until this null terminator is encountered.
+ Show Solution
#include <stdio.h>
int main() {
char str[] = "Hello World!";
int length = 0;
int i = 0;
// Loop until the null terminator ('\0') is found
while (str[i] != '\0') {
length++;
i++;
}
printf("The string is: \"%s\"\n", str);
printf("The length of the string is: %d\n", length);
return 0;
}Code language: C++ (cpp)
Explanation:
- An integer variable
lengthis initialized to 0. Awhileloop iterates through thestrarray. The loop condition isstr[i] != '\0', which means it continues as long as the current character is not the null terminator. - Inside the loop, the
lengthcounter is incremented, and the indeximoves to the next character. When the loop terminates,lengthholds the exact count of characters before the\0, which is the string’s length.
Exercise 3: Copy String
Problem Statement: Copy the contents of one string (source) to another string (destination) manually without using the built-in strcpy() function.
Given:
char source[] = "Copy Me!";
// Destination must be large enough to hold the source string + '\0'
char destination[20]; Code language: C++ (cpp)
Expected Output:
Source: Copy Me!
Destination: Copy Me!
+ Hint
- Iterate through the
sourcestring character by character, copying each element into the corresponding index of thedestinationstring. - Don’t forget to manually add the null terminator (
\0) to the end of thedestinationstring.
+ Show Solution
#include <stdio.h>
int main() {
char source[] = "Copy Me!";
// Destination must be large enough to hold the source string + '\0'
char destination[20];
int i = 0;
// Loop until the null terminator of the source string is reached
while (source[i] != '\0') {
destination[i] = source[i];
i++;
}
// Essential: Add the null terminator to the destination string
destination[i] = '\0';
printf("Source: %s\n", source);
printf("Destination: %s\n", destination);
return 0;
}Code language: C++ (cpp)
Explanation:
- The code uses a
whileloop to traverse thesourcestring. In each iteration,destination[i] = source[i];copies the character from the source to the destination. - The loop stops when
source[i]is the null terminator. - After the loop, the index
iis pointing to the position right after the last copied character. The linedestination[i] = '\0';manually places the null terminator, ensuring thedestinationarray is treated as a valid C string.
Exercise 4: Concatenate Strings
Problem Statement: Join two strings (str1 and str2) together, storing the result in the first string, without using the built-in strcat() function.
Given:
char str1[50] = "Hello ";
char str2[] = "World!";Code language: C++ (cpp)
Expected Output:
Concatenated string: Hello World!
+ Hint
First, find the length (the position of \0) of the first string (str1). Then, start copying characters from the second string (str2) into the first string, beginning at that null terminator position.
+ Show Solution
#include <stdio.h>
int main() {
// str1 must be large enough to hold both strings + '\0'
char str1[50] = "Hello ";
char str2[] = "World!";
int i, j;
// 1. Find the end of str1 (where '\0' is located)
for (i = 0; str1[i] != '\0'; i++);
// 2. Start copying str2 to str1 from index i
for (j = 0; str2[j] != '\0'; j++, i++) {
str1[i] = str2[j];
}
// 3. Add the null terminator at the new end of str1
str1[i] = '\0';
printf("Concatenated string: %s\n", str1);
return 0;
}Code language: C++ (cpp)
Explanation:
- The first
forloop finds the null terminator position instr1and stores its index ini. - The second
forloop starts iterating throughstr2using indexj. In the copy statement (str1[i] = str2[j];), thestr1indexiis incremented along withj(done in the loop update clause). This ensures characters fromstr2are placed sequentially after the original content ofstr1. - Finally, a new null terminator is placed at the very end of the resulting string in
str1.
Exercise 5: Compare Strings
Problem Statement: Check if two strings (str1 and str2) are identical (case-sensitive) and determine the result without using the built-in strcmp() function.
Given:
char str1[] = "apple";
char str2[] = "apple";Code language: C++ (cpp)
Expected Output:
The strings are identical.
+ Hint
- Compare characters at corresponding indices one by one. If at any point the characters are different, the strings are not identical.
- If the loop finishes and both strings’ null terminators were reached simultaneously, they are identical.
+ Show Solution
#include <stdio.h>
#include <stdbool.h>
int main() {
char str1[] = "apple";
char str2[] = "apple";
bool identical = true;
int i = 0;
// Loop as long as characters match AND we haven't hit the end of either string
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] != str2[i]) {
identical = false; // Mismatch found
break;
}
i++;
}
// Final check: If one string is longer than the other (one ended, the other didn't)
if (str1[i] != '\0' || str2[i] != '\0') {
identical = false;
}
if (identical) {
printf("The strings are identical.\n");
} else {
printf("The strings are NOT identical.\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The program uses a
whileloop to compare characters at indexi. The loop continues only if both strings still have characters to compare. Ifstr1[i]is not equal tostr2[i], theidenticalflag is set tofalse, and the loop breaks. - The check after the loop is crucial:
if (str1[i] != '\0' || str2[i] != '\0')handles the case where one string is a prefix of the other (e.g., “app” and “apple”). If this condition is true, they have different lengths, so they are not identical.
Exercise 6: Convert to Uppercase
Problem Statement: Convert all lowercase characters in a given string to their corresponding uppercase characters. Leave all other characters (uppercase, digits, symbols) unchanged.
Given:
char str[] = "c Programming Is Fun 123";Code language: C++ (cpp)
Expected Output:
Uppercase string: C PROGRAMMING IS FUN 123
+ Hint
Use a loop to traverse the string. Within the loop, check if a character is in the lowercase range (from ‘a’ to ‘z’). If it is, convert it by subtracting the difference between ‘a’ and ‘A’, or use the toupper() function (if allowed).
+ Show Solution
#include <stdio.h>
// #include <ctype.h> // Can be used for a simpler solution with toupper()
int main() {
char str[] = "c Programming Is Fun 123";
int i = 0;
while (str[i] != '\0') {
// Check if the character is in the lowercase range
if (str[i] >= 'a' && str[i] <= 'z') {
// Conversion logic: 'a' - 'A' is the difference (32 in ASCII)
str[i] = str[i] - ('a' - 'A');
// Alternatively, using ctype.h: str[i] = toupper(str[i]);
}
i++;
}
printf("Uppercase string: %s\n", str);
return 0;
}Code language: C++ (cpp)
Explanation:
- The program iterates through the string. The
ifcondition checks if the ASCII value of the current character falls within the lowercase range (‘a’ to ‘z’). If it does, the character is converted. - In ASCII, the uppercase letters are sequentially ordered, and the corresponding lowercase letters are 32 positions higher. By subtracting the difference
('a' - 'A')(which is 32), the character’s ASCII value is shifted back to its uppercase equivalent.
Exercise 7: Convert to Lowercase
Problem Statement: Convert all uppercase characters in a given string to their corresponding lowercase characters. Leave all other characters (lowercase, digits, symbols) unchanged.
Given:
char str[] = "C PrOgRaMmInG Is AwEsOmE";Code language: C++ (cpp)
Expected Output:
Lowercase string: c programming is awesome
+ Hint
This is the reverse of the previous exercise. Check if a character is in the uppercase range (from ‘A’ to ‘Z’). If it is, convert it by adding the difference between ‘a’ and ‘A’.
+ Show Solution
#include <stdio.h>
// #include <ctype.h> // Can be used for a simpler solution with tolower()
int main() {
char str[] = "C PrOgRaMmInG Is AwEsOmE";
int i = 0;
while (str[i] != '\0') {
// Check if the character is in the uppercase range
if (str[i] >= 'A' && str[i] <= 'Z') {
// Conversion logic: 'a' - 'A' is the difference (32 in ASCII)
str[i] = str[i] + ('a' - 'A');
// Alternatively, using ctype.h: str[i] = tolower(str[i]);
}
i++;
}
printf("Lowercase string: %s\n", str);
return 0;
}Code language: C++ (cpp)
Explanation:
- Similar to the uppercase conversion, the
ifcondition checks if the current character is within the uppercase ASCII range. - To convert it to lowercase, the difference
('a' - 'A')(which is 32) is added to the character’s ASCII value. This shifts the value forward by 32 positions, converting it from its uppercase form to its corresponding lowercase form.
Exercise 8: Toggle Case
Problem Statement: Toggle the case of every alphabet character in a string: convert uppercase characters to lowercase, and lowercase characters to uppercase.
Given:
char str[] = "HeLlO wOrLd 123";Code language: C++ (cpp)
Expected Output:
Toggled string: hElLo WoRlD 123
+ Hint
Use two separate if/else if conditions within the loop. One checks for the lowercase range and applies the uppercase conversion logic; the other checks for the uppercase range and applies the lowercase conversion logic.
+ Show Solution
#include <stdio.h>
int main() {
char str[] = "HeLlO wOrLd 123";
int i = 0;
int diff = 'a' - 'A'; // The ASCII difference (32)
while (str[i] != '\0') {
if (str[i] >= 'a' && str[i] <= 'z') {
// Convert lowercase to uppercase (subtract diff)
str[i] = str[i] - diff;
} else if (str[i] >= 'A' && str[i] <= 'Z') {
// Convert uppercase to lowercase (add diff)
str[i] = str[i] + diff;
}
// Other characters (digits, spaces) are ignored
i++;
}
printf("Toggled string: %s\n", str);
return 0;
}Code language: C++ (cpp)
Explanation:
- The code traverses the string and checks two conditions for each character. If the character is lowercase (
'a'to'z'), the differencediffis subtracted to move it to uppercase. - If the character is uppercase (
'A'to'Z'), the differencediffis added to move it to lowercase. Any character that doesn’t meet either of these criteria (like digits, spaces, or symbols) remains unchanged.
Exercise 9: Vowels and Consonants
Problem Statement: Count the total number of vowels (A, E, I, O, U, and their lowercase counterparts) and consonants in a given string.
Given:
char str[] = "Programming In C is fun.";Code language: C++ (cpp)
Expected Output:
String: Programming In C is fun.
Total Vowels: 6
Total Consonants: 13
+ Hint
Use an if/else if structure. First, ensure the character is an alphabet (check the entire range ‘a’-‘z’ and ‘A’-‘Z’). Then, inside this check, use a complex if condition with logical OR (||) to check for all 10 possible vowels. Any alphabet that isn’t a vowel must be a consonant.
+ Show Solution
#include <stdio.h>
#include <ctype.h> // For tolower() to simplify the vowel check
int main() {
char str[] = "Programming In C is fun.";
int vowels = 0;
int consonants = 0;
int i = 0;
while (str[i] != '\0') {
char ch = tolower(str[i]); // Convert to lowercase for simplified check
// Check if the character is an alphabet
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
i++;
}
printf("String: %s\n", str);
printf("Total Vowels: %d\n", vowels);
printf("Total Consonants: %d\n", consonants);
return 0;
}Code language: C++ (cpp)
Explanation:
- The code iterates through the string. It first uses
tolower()from<ctype.h>to convert the character to lowercase, simplifying the vowel check. The outerifcondition ensures that the character is an alphabet. - The inner
ifcondition explicitly checks if the character matches any of the five lowercase vowels using the logical OR operator (||). If it is an alphabet and not a vowel, theelseblock increments theconsonantscount. Non-alphabetic characters (spaces, periods, digits) are correctly ignored.
Exercise 10: Words in a String
Problem Statement: Count the number of words in a given string (sentence). Assume words are separated by one or more spaces, and the string may start or end with spaces.
Given:
char str[] = "This is a test string";Code language: C++ (cpp)
Expected Output:
The string is: "This is a test string"
Total number of words: 5
+ Hint
A word count can be determined by counting transitions: a word starts when a non-space character is encountered immediately after a space character, or when the string starts with a non-space character. Use a flag variable to track whether the program is currently “inside a word.”
+ Show Solution
#include <stdio.h>
#include <ctype.h> // For isspace()
int main() {
// String starts/ends with spaces and has multiple spaces between words
char str[] = "This is a test string";
int word_count = 0;
// 0: outside a word, 1: inside a word
int is_word = 0;
int i = 0;
while (str[i] != '\0') {
if (isspace(str[i])) {
// Character is a space (or other whitespace)
is_word = 0;
} else if (is_word == 0) {
// Character is NOT a space AND we were previously outside a word
is_word = 1; // Now inside a word
word_count++; // Increment count (start of a new word)
}
i++;
}
printf("The string is: \"%s\"\n", str);
printf("Total number of words: %d\n", word_count);
return 0;
}Code language: C++ (cpp)
Explanation:
The code uses a state-machine approach with the is_word flag. The isspace() function (from <ctype.h>) reliably checks for any whitespace character (space, tab, newline).
- If a space is found, the
is_wordflag is reset to 0 (the program is “outside a word”). - If a non-space character is found and
is_wordwas 0 (meaning the previous character was a space or it’s the start of the string), it means a new word has begun. Theis_wordflag is set to 1, andword_countis incremented. This logic correctly handles leading/trailing spaces and multiple spaces between words by only counting the transition from a space/non-word state to a non-space/word state.
Exercise 11: Specific Character Count
Problem Statement: Write a C program to read a string and a single character from the user, and then count and print the total number of times that specific character appears in the string (case-sensitive).
Expected Output:
Enter a string: My name is Jessa
Enter the character to count: s
The character 's' appears 3 times in the string.
+ Hint
Read the string using fgets() and the character using scanf() (or getchar()). Iterate through the string using a loop and compare each string character with the target character using the equality operator (==).
+ Show Solution
#include <stdio.h>
int main() {
char str[100];
char target_char;
int count = 0;
int i = 0;
printf("Enter a string: ");
fgets(str, 100, stdin);
printf("Enter the character to count: ");
// Note: Using ' %c' handles any lingering newline/space from previous input
scanf(" %c", &target_char);
// Loop through the string until the null terminator
while (str[i] != '\0') {
if (str[i] == target_char) {
count++;
}
i++;
}
printf("The character '%c' appears %d times in the string.\n", target_char, count);
return 0;
}Code language: C++ (cpp)
Explanation:
The program takes the input string and the target character. The while loop iterates over the string elements. Inside the loop, the if condition checks if the character at the current index str[i] matches the target_char. If they match, the count is incremented. The process continues until the end of the string (\0) is reached, providing the total occurrences.
Exercise 12: First Occurrence
Problem Statement: Find the index (position) of the first occurrence of a specific character (provided by the user) within a given string. If the character is not found, report that as well.
Given:
char str[] = "programming";
char target = 'g';Code language: C++ (cpp)
Expected Output:
First occurrence of 'g' found at index: 3
+ Hint
Use a loop to traverse the string. As soon as the target character is matched, print the current index and use the break statement to immediately exit the loop. If the loop completes without a break, the character wasn’t found.
+ Show Solution
#include <stdio.h>
int main() {
char str[] = "programming";
char target = 'g';
int index = -1; // Initialize to -1 to indicate 'not found'
int i = 0;
while (str[i] != '\0') {
if (str[i] == target) {
index = i;
break; // Stop immediately after finding the first occurrence
}
i++;
}
if (index != -1) {
printf("First occurrence of '%c' found at index: %d\n", target, index);
} else {
printf("Character '%c' not found in the string.\n", target);
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The
indexvariable is initialized to-1. Thewhileloop iterates through the string. The momentstr[i]equals thetargetcharacter, the current indexiis stored inindex, and thebreakstatement terminates the loop, ensuring we only record the first match. - If the loop finishes without a
break,indexremains-1, triggering the “not found” message.
Exercise 13: Last Occurrence
Problem Statement: Find the index (position) of the last occurrence of a specific character (provided by the user) within a given string.
Given:
char str[] = "programming";
char target = 'g';Code language: C++ (cpp)
Expected Output:
Last occurrence of 'g' found at index: 10
+ Hint
Loop through the string as you normally would. Instead of stopping at the first match, simply update the index of the last found match in a variable. When the loop finishes (reaching \0), the variable will hold the index of the final match.
+ Show Solution
#include <stdio.h>
int main() {
char str[] = "programming";
char target = 'g';
int last_index = -1; // Initialize to -1
int i = 0;
while (str[i] != '\0') {
if (str[i] == target) {
// Keep updating the index whenever the target is found.
// The last update before the loop ends will be the last occurrence.
last_index = i;
}
i++;
}
if (last_index != -1) {
printf("Last occurrence of '%c' found at index: %d\n", target, last_index);
} else {
printf("Character '%c' not found in the string.\n", target);
}
return 0;
}Code language: C++ (cpp)
Explanation:
Unlike Exercise 12, this program does not use break. It iterates through the entire string. Every time the target character is found, the last_index variable is updated to the current index i. Because the loop progresses sequentially, the last value assigned to last_index will necessarily be the index of the character’s final appearance in the string.
Exercise 14: Character Frequency
Problem Statement: Calculate and print the frequency (count) of every lowercase alphabet character (‘a’ through ‘z’) present in a given string
Given:
char str[] = "Jessa";
int freq[26] = {0}; // Initialize all 26 counters to zeroCode language: C++ (cpp)
Expected Output:
Character Frequencies (a-z):
'a': 1
'e': 1
'j': 1
's': 2
+ Hint
Use an auxiliary integer array (size 26) to act as a frequency map. Use the character’s ASCII value to map it to an array index (e.g., 'a' maps to index 0, 'b' to index 1, etc. by subtracting 'a'). Iterate through the string, and for every lowercase letter, increment the corresponding counter in the frequency array.
+ Show Solution
#include <stdio.h>
#include <ctype.h>
int main() {
char str[] = "Programming in C is fun";
int freq[26] = {0}; // Initialize all 26 counters to zero
int i = 0;
while (str[i] != '\0') {
char ch = tolower(str[i]); // Handle both cases as one
// Check if the character is a lowercase alphabet
if (ch >= 'a' && ch <= 'z') {
// Map 'a' to index 0, 'b' to 1, etc.
int index = ch - 'a';
freq[index]++;
}
i++;
}
printf("Character Frequencies (a-z):\n");
for (i = 0; i < 26; i++) {
// Only print characters that appeared at least once
if (freq[i] > 0) {
// Convert index back to character: i + 'a'
printf("'%c': %d\n", (char)(i + 'a'), freq[i]);
}
}
return 0;
}Code language: C++ (cpp)
Explanation:
- An array
freq[26]is used to store counts. The loop traverses the string, converting each character to lowercase usingtolower(). - If the character is a letter, the key step is calculating the
indexby subtracting the ASCII value of'a'from the character’s value (ch - 'a'). This gives an index from 0 to 25, which is used to increment the counter in thefreqarray. A final loop iterates through thefreqarray, displaying the character (by adding'a'back to the index) and its count.
Exercise 15: Remove Specific Character
Problem Statement: Remove all occurrences of a specific character (e.g., ‘x’) from a string and shift the remaining characters to fill the gap.
Given:
char str[] = "eExxammpelle";
char char_to_remove = 'e';Code language: C++ (cpp)
Expected Output:
String after removing 'e': Exxammpll
+ Hint
- Use two pointers (indices): one to read from the original string (
read_index) and one to write to the modified string (write_index). - If the character being read is not the one to be removed, copy it to the
write_indexand increment both indices. If it is the one to be removed, only increment theread_index. Finally, ensure the null terminator is placed correctly.
+ Show Solution
#include <stdio.h>
int main() {
char str[] = "eExxammpelle";
char char_to_remove = 'e';
int read_index = 0;
int write_index = 0;
while (str[read_index] != '\0') {
if (str[read_index] != char_to_remove) {
// Character is NOT the one to remove: copy it and advance both indices
str[write_index] = str[read_index];
write_index++;
}
// If character IS the one to remove, only read_index advances, effectively skipping it
read_index++;
}
// Place the null terminator at the end of the new (shorter) string
str[write_index] = '\0';
printf("String after removing '%c': %s\n", char_to_remove, str);
return 0;
}Code language: C++ (cpp)
Explanation:
- This uses an in-place modification technique with two pointers.
read_indexalways moves forward, reading the original string.write_indexonly advances when a character is kept. - When
str[read_index]is the character to remove, theifblock is skipped, andread_indexadvances whilewrite_indexstays put. This causes the next good character to be written over the removed character’s position. Finally, the string is terminated at thewrite_indexposition.
Exercise 16: Non-Repeating Character
Problem Statement: Find and print the first non-repeating character in a given string. If all characters repeat, report that no unique character was found.
Given:
char str[] = "aabbccdeeff";Code language: C++ (cpp)
Expected Output:
First non-repeating character: 'd'
+ Hint
This is best solved using a two-pass approach with a frequency map (like Exercise 14).
- Pass 1: Populate a frequency array (size 26 or 256 for full ASCII) with counts of all characters.
- Pass 2: Iterate through the string again. For each character, check its count in the frequency array. The first character whose count is 1 is the first non-repeating character.
+ Show Solution
#include <stdio.h>
#include <string.h> // For strlen
int main() {
char str[] = "aabbccdeeff";
// Array to store frequency for all 256 ASCII characters
int freq[256] = {0};
int i;
// PASS 1: Calculate Frequency
for (i = 0; str[i] != '\0'; i++) {
freq[(int)str[i]]++;
}
// PASS 2: Find the first character with frequency 1
char first_non_repeat = '\0';
for (i = 0; str[i] != '\0'; i++) {
if (freq[(int)str[i]] == 1) {
first_non_repeat = str[i];
break;
}
}
if (first_non_repeat != '\0') {
printf("First non-repeating character: '%c'\n", first_non_repeat);
} else {
printf("No non-repeating character found.\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- This solution uses a larger frequency array (
freq[256]) to handle any character by using its ASCII value as the index. - Pass 1 builds the frequency map. Pass 2 is the crucial part: it iterates through the original string in order. The first character encountered that has a frequency count of
1(meaning it appeared only once) is guaranteed to be the first non-repeating character, so the loop breaks and the result is printed.
Exercise 17: Remove Extra Spaces
Problem Statement: Modify a string in place to remove all leading spaces, trailing spaces, and reduce multiple consecutive spaces between words to just a single space.
Given:
char str[] = " This is a test. ";Code language: C++ (cpp)
Expected Output:
Normalized string: "This is a test."
+ Hint
This is a tricky two-step problem.
- Normalize: Use two pointers (read/write) to iterate and ensure only one space separates words, skipping all others.
- Trim: Find the start and end of the normalized string to remove leading and trailing spaces.
+ Show Solution
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
char str[] = " This is a test. ";
int read_idx = 0;
int write_idx = 0;
int i;
// 1. Skip leading spaces
while (isspace(str[read_idx])) {
read_idx++;
}
// 2. Normalize spaces (reduce multiple to one)
while (str[read_idx] != '\0') {
if (isspace(str[read_idx])) {
// If it's a space, only write it if the previous character wasn't already a space
if (write_idx > 0 && !isspace(str[write_idx - 1])) {
str[write_idx++] = ' ';
}
} else {
// It's a non-space character, just copy it
str[write_idx++] = str[read_idx];
}
read_idx++;
}
// 3. Remove trailing space (if one was written before the final '\0')
if (write_idx > 0 && isspace(str[write_idx - 1])) {
write_idx--;
}
// 4. Terminate the new string
str[write_idx] = '\0';
printf("Normalized string: \"%s\"\n", str);
return 0;
}Code language: C++ (cpp)
Explanation:
- The code first skips over any leading whitespace. Then, it uses the read/write pointer technique.
- The core logic is: only write a space if the current character is a space AND the character just written (
str[write_idx - 1]) was not a space. All subsequent spaces are skipped. - Finally, the trailing space check ensures that if the last non-null character written was a space (because of a trailing space in the original string), the
write_idxis moved back one position before the null terminator is placed, effectively trimming the trailing space.
Exercise 18: Check For Digit
Problem Statement: Determine if a string consists entirely of digit characters (‘0’ through ‘9’). The string must contain at least one character.
Given:
char str1[] = "12345";
char str2[] = "123a45";Code language: C++ (cpp)
Expected Output:
String: "12345"
Result: Contains only digits.
+ Hint
Loop through the string. Use the isdigit() function from <ctype.h> or a manual check (str[i] >= '0' && str[i] <= '9'). If any character is found that is not a digit, immediately flag the string as invalid and stop checking.
+ Show Solution
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
int main() {
char str1[] = "12345";
char str2[] = "123a45";
char *str = str1; // Test with str1 first
bool all_digits = true;
int i = 0;
if (str[0] == '\0') {
all_digits = false; // String is empty
} else {
while (str[i] != '\0') {
if (!isdigit(str[i])) { // Check if character is NOT a digit
all_digits = false;
break;
}
i++;
}
}
printf("String: \"%s\"\n", str);
if (all_digits) {
printf("Result: Contains only digits.\n");
} else {
printf("Result: Contains non-digit characters.\n");
}
// Optional: Re-test with str2
// str = str2; ...
// [Re-run logic here to test str2]
return 0;
}Code language: C++ (cpp)
Explanation:
- The program first checks if the string is empty. The
whileloop iterates through the string. Theisdigit()function checks if a character is a decimal digit. The logic uses the negation operator (!) to check if the character is not a digit. - If a non-digit character is found, the
all_digitsflag is set tofalse, and thebreakstatement halts the process immediately, as no further checking is necessary.
Exercise 19: Extract Substring
Problem Statement: Extract a substring from a source string given a starting position (index) and the desired length. The resulting substring should be stored in a new string.
Given:
char source[] = "Programming In C";
int start_index = 0; // Start from 'r' (index 4)
int length = 7; // Extract 7 characters ("ramming")
char destination[15]; // Destination buffer sizeCode language: C++ (cpp)
Expected Output:
Source: Programming In C
Substring: Program
+ Hint
Use a loop that starts at the given start_index of the source string and runs for length iterations, or until the source string’s null terminator is reached. Copy characters to the destination string, and remember to null-terminate the destination.
+ Show Solution
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "ProgrammingInC";
int start_index = 4; // Start from 'r' (index 4)
int length = 7; // Extract 7 characters ("ramming")
char destination[15]; // Destination buffer size
int i;
// Ensure indices are valid (omitted full validation for brevity)
if (start_index >= strlen(source)) {
printf("Error: Start index out of bounds.\n");
return 1;
}
// Loop runs for 'length' times
for (i = 0; i < length; i++) {
// Check if the source string ends before 'length' is complete
if (source[start_index + i] == '\0') {
break;
}
destination[i] = source[start_index + i];
}
// Null-terminate the destination string
destination[i] = '\0';
printf("Source: %s\n", source);
printf("Substring: %s\n", destination);
return 0;
}Code language: C++ (cpp)
Explanation:
- The
forloop is designed to run exactlylengthtimes, controlled by the counteri. In each iteration, the character from thesourcestring at indexstart_index + iis copied to thedestinationstring at indexi. - An internal check (
if (source[start_index + i] == '\0')) ensures that the copying stops prematurely if the original string ends before the requestedlengthis reached. Finally,destination[i] = '\0';adds the required null terminator at the end of the newly created substring.
Exercise 20: Search Substring
Problem Statement: Determine if a smaller string (needle) exists anywhere within a larger string (haystack). If found, report the starting index of its first occurrence.
Given:
char haystack[] = "This is a search test";
char needle[] = "search";Code language: C++ (cpp)
Expected Output:
Haystack: "This is a search test"
Needle: "search"
Substring found at index: 10
+ Hint
- Use nested loops. The outer loop iterates through the
haystack, looking for the first character of theneedle. - The inner loop compares subsequent characters of the
haystack(starting from the match point) with the entireneedlestring. If the inner loop successfully completes, a match is found.
+ Show Solution
#include <stdio.h>
#include <stdbool.h>
int main() {
char haystack[] = "This is a search test";
char needle[] = "search";
int i, j;
bool found = false;
int start_index = -1;
// Outer loop: iterates through the haystack (potential starting points)
for (i = 0; haystack[i] != '\0'; i++) {
// Inner loop: compares needle against haystack starting at index i
for (j = 0; needle[j] != '\0'; j++) {
// If a mismatch occurs, break the inner loop
if (haystack[i + j] == '\0' || haystack[i + j] != needle[j]) {
break;
}
}
// If the inner loop finished because needle[j] hit '\0', it means a match
if (needle[j] == '\0') {
found = true;
start_index = i;
break; // Stop searching after the first match
}
}
printf("Haystack: \"%s\"\n", haystack);
printf("Needle: \"%s\"\n", needle);
if (found) {
printf("Substring found at index: %d\n", start_index);
} else {
printf("Substring not found.\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The outer loop (
i) controls the potential starting position of the match in thehaystack. The inner loop (j) compares characters. - The key check is
haystack[i + j] != needle[j]. If the characters match,jincrements, and the comparison continues to the next character of theneedle. If the inner loop breaks due to a mismatch, the outer loop continues to the next position in thehaystack. - If the inner loop completes successfully (meaning
needle[j]is the null terminator), it implies every character in theneedlematched, and the match is confirmed at indexi.
Exercise 21: Reverse String
Problem Statement: Reverse the order of characters in a given string in place (without using an auxiliary string).
Given:
char str[] = "programming";Code language: C++ (cpp)
Expected Output:
Original string: programming
Reversed string: gnimmargorp
+ Hint
- Use the two-pointer or swap technique. Initialize one index at the start of the string and another at the end of the string.
- In a loop, swap the characters at these two indices, then move the start index forward and the end index backward until they meet or cross over.
+ Show Solution
#include <stdio.h>
#include <string.h>
void swap_char(char *a, char *b) {
char temp = *a;
*a = *b;
*b = temp;
}
int main() {
char str[] = "programming";
int len = strlen(str);
int start = 0;
int end = len - 1;
printf("Original string: %s\n", str);
// Loop until the pointers meet or cross
while (start < end) {
// Swap characters at start and end indices
swap_char(&str[start], &str[end]);
// Move pointers inward
start++;
end--;
}
printf("Reversed string: %s\n", str);
return 0;
}Code language: C++ (cpp)
Explanation:
- The
strlen()function finds the length of the string.startis initialized to 0 andendto the index of the last character. - The
whileloop continues as long asstartis less thanend. Inside the loop, theswap_charfunction exchanges the characters pointed to by the two indices. By incrementingstartand decrementingendsimultaneously, the process moves inward from both ends, ensuring that the entire string is reversed in place by the time the pointers meet.
Exercise 22: Palindrome Check
Problem Statement: Determine if a string is a palindrome (reads the same forwards and backwards, ignoring case and punctuation for a robust check, but for simplicity, only consider the exact characters).
Given:
char str[] = "madam";Code language: C++ (cpp)
Expected Output:
String: madam
Result: It is a palindrome.
+ Hint
- Use the two-pointer technique similar to reversing a string (Exercise 21).
- Compare the character at the start index with the character at the end index. If a mismatch is found at any point, the string is not a palindrome, and you can stop immediately.
- If the pointers meet or cross without finding a mismatch, it is a palindrome.
+ Show Solution
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main() {
char str[] = "madam";
int len = strlen(str);
int start = 0;
int end = len - 1;
bool is_palindrome = true;
while (start < end) {
// Compare characters
if (str[start] != str[end]) {
is_palindrome = false;
break; // Mismatch found, not a palindrome
}
// Move pointers inward
start++;
end--;
}
printf("String: %s\n", str);
if (is_palindrome) {
printf("Result: It is a palindrome.\n");
} else {
printf("Result: It is NOT a palindrome.\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The two-pointer technique is used to check symmetry.
- The loop compares characters from the outside-in. If
str[start]does not equalstr[end], theis_palindromeflag is set tofalse, and the loop is immediately terminated viabreak. - If the loop completes, it means all corresponding characters from the start and end matched perfectly, confirming the string is a palindrome.
Exercise 23: Reverse Words
Problem Statement: Reverse the order of words in a sentence while keeping the characters within each word in their original order (e.g., “C language programming” becomes “programming language C”).
Given:
char str[] = "C programming is fun";Code language: C++ (cpp)
Expected Output:
Original: C programming is fun
Reversed words: fun is programming C
+ Hint
This is a two-step process:
- Reverse the entire string (using the technique from Exercise 21). This reverses the word order and the characters within each word.
- Reverse each word individually to restore the internal character order. Find the boundaries of each word (non-space characters delimited by spaces or null terminator) and apply the reversal technique only within those boundaries.
+ Show Solution
#include <stdio.h>
#include <string.h>
// Function to swap characters (from Ex 21)
void swap_char(char *a, char *b) {
char temp = *a;
*a = *b;
*b = temp;
}
// Function to reverse a segment of the string (in place)
void reverse_segment(char *str, int start, int end) {
while (start < end) {
swap_char(&str[start], &str[end]);
start++;
end--;
}
}
int main() {
char str[] = "C programming is fun";
int len = strlen(str);
int word_start = 0;
int i;
printf("Original: %s\n", str);
// STEP 1: Reverse the entire string ("nuf si gnimmargorp C")
reverse_segment(str, 0, len - 1);
// STEP 2: Reverse each word individually
for (i = 0; i <= len; i++) {
if (str[i] == ' ' || str[i] == '\0') {
// Found end of a word (or end of string)
reverse_segment(str, word_start, i - 1);
// Set the start of the next word to the position after the space
word_start = i + 1;
}
}
printf("Reversed words: %s\n", str);
return 0;
}Code language: C++ (cpp)
Explanation:
- First, the entire string is reversed, which places the words in the correct final order but leaves the characters in each word backwards.
- The second
forloop iterates through the reversed string, looking for spaces or the null terminator (\0) to identify word boundaries. - When a boundary is found, the
reverse_segmentfunction is called to reverse the characters only within that identified word’s boundaries, thus correcting the word’s internal character order.
Exercise 24: Remove Duplicates
Problem Statement: Remove duplicate characters from a string, keeping only the first occurrence of each character. The operation should be performed in place.
Given:
char str[] = "programmingisgreat";Code language: C++ (cpp)
Expected Output:
Original: programmingisgreat
No duplicates: progaminset
+ Hint
- Use an auxiliary data structure (like a boolean array, size 256 for all ASCII characters) to track which characters have already been seen.
- Use the read/write pointer technique (like Exercise 15). If a character hasn’t been seen, mark it as seen and copy it to the
write_index; otherwise, just advance theread_index.
+ Show Solution
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "programmingisgreat";
// Flag array for all 256 possible ASCII chars
int seen[256] = {0};
int read_index = 0;
int write_index = 0;
printf("Original: %s\n", str);
while (str[read_index] != '\0') {
unsigned char current_char = str[read_index]; // Use unsigned char for index safety
// Check if the character has NOT been seen yet
if (seen[current_char] == 0) {
// 1. Mark as seen
seen[current_char] = 1;
// 2. Copy the character (keep it)
str[write_index] = str[read_index];
write_index++;
}
// Always move to the next character in the original string
read_index++;
}
// Null-terminate the new string
str[write_index] = '\0';
printf("No duplicates: %s\n", str);
return 0;
}Code language: C++ (cpp)
Explanation:
- The
seenarray acts as a simple hash set (or frequency map, where we only care about 0 or 1). - The read/write pointer technique ensures in-place modification. For every character, its ASCII value is used to index into the
seenarray. - If the value is 0 (unseen), the character is copied to the
write_indexposition, and its correspondingseenentry is set to 1. - If the value is 1 (seen), the character is skipped, and only
read_indexadvances, effectively removing the duplicate.
Exercise 25: Check Anagrams
Problem Statement: Determine if two strings are anagrams of each other (meaning they contain the exact same characters with the same frequencies, regardless of order). Case and spaces should be ignored for a robust check.
Given:
char str1[] = "listen";
char str2[] = "silent";Code language: C++ (cpp)
Expected Output:
String 1: listen
String 2: silent
Result: They are anagrams.
+ Hint
The easiest way to check for anagrams is using a frequency map.
- Use an array (size 26) to track frequencies.
- Iterate through the first string: increment the count for each alphabet character.
- Iterate through the second string: decrement the count for each alphabet character.
- Finally, check the frequency array. If all counters are zero, the strings are anagrams.
+ Show Solution
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main() {
char str1[] = "listen";
char str2[] = "silent";
int freq[26] = {0}; // Frequency map for a-z
int i;
bool is_anagram = true;
// Pass 1: Increment counts for str1
for (i = 0; str1[i] != '\0'; i++) {
if (isalpha(str1[i])) {
freq[tolower(str1[i]) - 'a']++;
}
}
// Pass 2: Decrement counts for str2
for (i = 0; str2[i] != '\0'; i++) {
if (isalpha(str2[i])) {
freq[tolower(str2[i]) - 'a']--;
}
}
// Pass 3: Check frequency array
for (i = 0; i < 26; i++) {
if (freq[i] != 0) {
is_anagram = false;
break;
}
}
printf("String 1: %s\n", str1);
printf("String 2: %s\n", str2);
if (is_anagram) {
printf("Result: They are anagrams.\n");
} else {
printf("Result: They are NOT anagrams.\n");
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The core of this solution lies in using the
freq[26]array. By first incrementing counts for characters in the first string and then decrementing them for characters in the second string, we achieve a balance check. - If the strings are true anagrams, every character introduced by
str1must be perfectly canceled out by a character instr2. Therefore, a final check for all zeros in thefreqarray confirms the anagram status. - The use of
isalpha()andtolower()ensures case and non-alphabetic characters are handled correctly.
Exercise 26: Sort String
Problem Statement: Sort the characters of a string alphabetically (e.g., “Jessa” becomes “Jaess”).
Given:
char str[] = "Jessa";Code language: C++ (cpp)
Expected Output:
Original: Jessa
Sorted: Jaess
+ Hint
- Since a string is just a character array, standard sorting algorithms can be applied. The Bubble Sort algorithm is simple to implement and sufficient for this exercise.
- Use two nested loops to compare adjacent characters and swap them if they are in the wrong order.
+ Show Solution
#include <stdio.h>
#include <string.h>
void swap_char(char *a, char *b) {
char temp = *a;
*a = *b;
*b = temp;
}
int main() {
char str[] = "Jessa";
int len = strlen(str);
int i, j;
printf("Original: %s\n", str);
// Implement Bubble Sort
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - i - 1; j++) {
// Compare adjacent characters (using ASCII values)
if (str[j] > str[j + 1]) {
swap_char(&str[j], &str[j + 1]);
}
}
}
printf("Sorted: %s\n", str);
return 0;
}Code language: C++ (cpp)
Explanation:
The solution uses the Bubble Sort algorithm
- The outer loop controls the number of passes, and the inner loop handles the actual comparisons and swaps. In the inner loop,
if (str[j] > str[j + 1])compares the ASCII values of two adjacent characters. - If the character at the lower index (
j) is greater than the character at the higher index (j + 1), they are swapped, moving the larger character toward the end of the string. This repeated process eventually places all characters in ascending ASCII (alphabetical) order.
Exercise 27: Highest Frequency Character
Problem Statement: Find and print the character that appears most frequently in a given string.
Given:
char str[] = "successfully";Code language: C++ (cpp)
Expected Output:
String: successfully
Highest frequency character: 's' (Count: 3)
+ Hint
This is a direct application of the frequency map technique (like Exercise 14).
- Create a frequency array (size 256) and populate it in a single pass.
- After counting all characters, iterate through the frequency array to find the index that holds the maximum count.
- The index corresponding to the maximum count is the ASCII value of the most frequent character.
+ Show Solution
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "successfully";
int freq[256] = {0};
int i;
int max_freq = -1;
int max_index = 0; // ASCII value of the most frequent character
// Pass 1: Calculate Frequency
for (i = 0; str[i] != '\0'; i++) {
freq[(int)str[i]]++;
}
// Pass 2: Find the maximum frequency and its index
for (i = 0; i < 256; i++) {
if (freq[i] > max_freq) {
max_freq = freq[i];
max_index = i;
}
}
printf("String: %s\n", str);
printf("Highest frequency character: '%c' (Count: %d)\n", (char)max_index, max_freq);
return 0;
}Code language: C++ (cpp)
Explanation:
- The solution uses a
freq[256]array to count all characters. - The second loop iterates through this
freqarray from index 0 to 255. It keeps track ofmax_freq(the highest count found so far) andmax_index(the corresponding ASCII value). - Whenever a higher frequency is found, both variables are updated. After checking all 256 possible characters,
max_indexholds the ASCII value of the character with the greatest number of occurrences, which is then cast back to acharfor printing.
Exercise 28: String to Integer (atoi)
Problem Statement: Implement a function to convert a string of digits into its corresponding integer value (e.g., “123” to 123) without using the built-in atoi(). The function should handle positive numbers and optionally, a leading sign.
Given:
char str1[] = "123";
char str2[] = "-456";Code language: C++ (cpp)
Expected Output:
123 -> 123
-456 -> -456
+ Hint
Initialize the result to 0. Iterate through the string. For each digit character, first convert the character digit to its integer value (by subtracting the ASCII value of ‘0’). Then, update the result using the formula: result = (result * 10) + digit_value.
+ Show Solution
#include <stdio.h>
#include <stdbool.h>
int string_to_int(const char *str) {
int result = 0;
int sign = 1;
int i = 0;
// 1. Handle optional sign
if (str[i] == '-') {
sign = -1;
i++;
} else if (str[i] == '+') {
i++;
}
// 2. Process digits
while (str[i] != '\0') {
// Check if it's a valid digit
if (str[i] >= '0' && str[i] <= '9') {
// Convert character digit to integer value
int digit_value = str[i] - '0';
// Update result: (previous result * 10) + new digit
result = (result * 10) + digit_value;
} else {
// Stop on first non-digit character (after sign)
break;
}
i++;
}
return result * sign;
}
int main() {
char str1[] = "123";
char str2[] = "-456";
printf("123 -> %d\n", string_to_int(str1));
printf("-456 -> %d\n", string_to_int(str2));
return 0;
}Code language: C++ (cpp)
Explanation:
The code first checks for a leading sign (+ or -) and stores it in the sign variable, advancing the index i. The while loop iterates through the digits. The core logic is result = (result * 10) + digit_value. For the string “123”:
- ‘1’:
(0 * 10) + 1= 1 - ‘2’:
(1 * 10) + 2= 12 - ‘3’:
(12 * 10) + 3= 123 The character conversionstr[i] - '0'uses the sequential nature of ASCII values (e.g.,'5'–'0'equals the integer 5). Finally, theresultis multiplied by the storedsign.
Exercise 29: Integer to String (itoa)
Problem Statement: Implement a function to convert an integer to its string representation (e.g., 123 to “123”) without using the built-in sprintf() or itoa(). The function should handle positive and negative integers.
Given:
int num1 = 12345;
int num2 = -987;Code language: C++ (cpp)
Expected Output:
12345 -> "12345"
-987 -> "987"
+ Hint
The easiest way to extract digits from an integer is by using the modulo operator (% 10) and integer division (/ 10). This process naturally extracts digits in reverse order (least significant digit first). Therefore, after extracting and storing the digits, the resulting string must be reversed (using the technique from Exercise 21).
+ Show Solution
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h> // For abs()
// Function to reverse a segment of the string (from Ex 21/23)
void reverse_segment(char *str, int start, int end) {
char temp;
while (start < end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
// Converts integer n into string s (assumes s is large enough)
void int_to_string(int n, char s[]) {
int i = 0;
bool is_negative = false;
if (n < 0) {
is_negative = true;
n = -n; // Work with positive version
}
// Handle case for n=0
if (n == 0) {
s[i++] = '0';
} else {
// Extract digits using modulo and division (reversed order)
while (n > 0) {
// '0' is added to integer digit to get its ASCII character
s[i++] = (n % 10) + '0';
n /= 10;
}
}
// Add the sign if necessary
if (is_negative) {
s[i++] = '-';
}
s[i] = '\0'; // Null terminate the reversed string
// Reverse the string to get the correct order
reverse_segment(s, 0, i - 1);
}
int main() {
char buffer[20];
int num1 = 12345;
int num2 = -987;
int_to_string(num1, buffer);
printf("12345 -> \"%s\"\n", buffer); // Output: "12345"
int_to_string(-num2, buffer);
printf("-987 -> \"%s\"\n", buffer); // Output: "-987"
return 0;
}Code language: C++ (cpp)
Explanation:
- The function first handles the sign and converts the number to its positive magnitude.
- It then enters a
whileloop:n % 10extracts the last digit (e.g., 123 % 10 = 3), and adding'0'converts this integer to its character representation.n / 10discards the last digit. - This process populates the string backwards. After all digits and the sign are placed, the entire string (from index 0 to
i-1) is reversed using the auxiliary function to get the correct final order.
Exercise 30: URL Parser (Simple)
Problem Statement: Given a simple URL string (e.g., “http://www.example.com/page“), extract and print the protocol (“http”), domain (“www.example.com“), and path (“/page”).
Given:
char url[] = "https://www.google.com/page/c_programming";Code language: C++ (cpp)
Expected Output:
URL: https://www.google.com/search/c_programming
Protocol: https
Domain: www.google.com
Path: /search/c_programming
+ Hint
- The key is finding specific delimiter sequences.
- The protocol is delimited by
://. The domain ends either at the first/after the protocol or at the end of the string. The path starts after the domain delimiter. Use the built-instrstr()(or implement its logic) to find the delimiters.
+ Show Solution
#include <stdio.h>
#include <string.h>
int main() {
char url[] = "https://www.google.com/search/c_programming";
char *protocol_end = strstr(url, "://");
char *domain_start = NULL;
char *path_start = NULL;
int i;
printf("URL: %s\n", url);
// 1. EXTRACT PROTOCOL
if (protocol_end != NULL) {
int proto_len = protocol_end - url;
printf("Protocol: ");
for (i = 0; i < proto_len; i++) {
printf("%c", url[i]);
}
printf("\n");
domain_start = protocol_end + 3; // Move past "://"
} else {
// Handle case where no protocol is present
domain_start = url;
}
// 2. EXTRACT DOMAIN
path_start = strchr(domain_start, '/'); // Find first '/' after protocol
if (path_start != NULL) {
int domain_len = path_start - domain_start;
printf("Domain: ");
for (i = 0; i < domain_len; i++) {
printf("%c", domain_start[i]);
}
printf("\n");
// 3. EXTRACT PATH
printf("Path: %s\n", path_start);
} else {
// Case where URL ends after domain (e.g., "http://google.com")
printf("Domain: %s\n", domain_start);
printf("Path: /\n"); // Path defaults to root
}
return 0;
}Code language: C++ (cpp)
Explanation:
The solution uses pointer arithmetic combined with string searching functions.
- Protocol:
strstr(url, "://")finds the position of the delimiter. The length of the protocol is calculated by subtracting the start pointer of the URL from the position of the delimiter (protocol_end - url). - Domain: The domain starts immediately after the delimiter (
protocol_end + 3).strchr(domain_start, '/')finds the first forward slash after the protocol, which marks the end of the domain. - Path: If a slash is found, the path starts at that position (
path_start). Since the path goes until the end of the string, it can be printed directly using the%sformat specifier. The domain itself is printed by iterating fromdomain_startup to the character beforepath_start.

Leave a Reply