Basic String Programming Questions
I am Jyotiprakash, a deeply driven computer systems engineer, software developer, teacher, and philosopher. With a decade of professional experience, I have contributed to various cutting-edge software products in network security, mobile apps, and healthcare software at renowned companies like Oracle, Yahoo, and Epic. My academic journey has taken me to prestigious institutions such as the University of Wisconsin-Madison and BITS Pilani in India, where I consistently ranked among the top of my class.
At my core, I am a computer enthusiast with a profound interest in understanding the intricacies of computer programming. My skills are not limited to application programming in Java; I have also delved deeply into computer hardware, learning about various architectures, low-level assembly programming, Linux kernel implementation, and writing device drivers. The contributions of Linus Torvalds, Ken Thompson, and Dennis Ritchie—who revolutionized the computer industry—inspire me. I believe that real contributions to computer science are made by mastering all levels of abstraction and understanding systems inside out.
In addition to my professional pursuits, I am passionate about teaching and sharing knowledge. I have spent two years as a teaching assistant at UW Madison, where I taught complex concepts in operating systems, computer graphics, and data structures to both graduate and undergraduate students. Currently, I am an assistant professor at KIIT, Bhubaneswar, where I continue to teach computer science to undergraduate and graduate students. I am also working on writing a few free books on systems programming, as I believe in freely sharing knowledge to empower others.
Here are 10 C programming exercises that involve strings:
String Length: Write a program to calculate and print the length of a given string without using the
strlenfunction.String Reversal: Create a program that reverses a given string. For example, if the input is "hello," the output should be "olleh."
String Concatenation: Implement a function to concatenate two strings without using the standard library function
strcat.String Comparison: Write a program that compares two strings without using the
strcmpfunction and prints whether they are equal or not.Substring Search: Develop a function to check if a given substring exists in a larger string. Return the position of the first occurrence if found, otherwise return -1.
Palindrome Check: Create a program to determine if a given string is a palindrome (reads the same backward as forward).
Count Vowels and Consonants: Write a function to count the number of vowels and consonants in a given string.
String Tokenization: Implement a program that tokenizes a given sentence into words. Print each word on a new line.
String Compression: Develop a function to compress a string by replacing repeated characters with a single occurrence followed by the count. For example, "aaabbbcc" should become "a3b3c2."
Remove Duplicates: Write a program to remove duplicate characters from a string without using any additional data structures. The resulting string should maintain the order of characters.
These exercises cover a range of string-related concepts and will help you practice and strengthen your skills in C programming. I have solved all of the above with explanatory comments. You should first make a sincere attempt at solving these problems before looking at the solutions.
String Length:
#include <stdio.h> // Function to calculate the length of a string int stringLength(const char *str) { int length = 0; // Iterate through the characters until the null terminator is encountered while (str[length] != '\0') { length++; } return length; } int main() { const char *inputString = "Hello, World!"; int length = stringLength(inputString); printf("Length of the string: %d\n", length); return 0; }String Reversal:
#include <stdio.h> // Function to reverse a string void reverseString(char *str) { int length = stringLength(str); int i, j; // Swap characters from the beginning and end of the string for (i = 0, j = length - 1; i < j; i++, j--) { char temp = str[i]; str[i] = str[j]; str[j] = temp; } } int main() { char inputString[] = "Hello"; // Print the original string printf("Original String: %s\n", inputString); // Reverse the string and print the result reverseString(inputString); printf("Reversed String: %s\n", inputString); return 0; }String Concatenation:
#include <stdio.h> // Function to concatenate two strings void concatenateStrings(char *destination, const char *source) { int destLength = stringLength(destination); int i, j; // Move to the end of the destination string for (i = 0; source[i] != '\0'; i++) { destination[destLength + i] = source[i]; } // Add null terminator to the end of the concatenated string destination[destLength + i] = '\0'; } int main() { char str1[50] = "Hello, "; const char str2[] = "World!"; // Concatenate str2 to str1 and print the result concatenateStrings(str1, str2); printf("Concatenated String: %s\n", str1); return 0; }String Comparison:
#include <stdio.h> // Function to compare two strings int compareStrings(const char *str1, const char *str2) { int i = 0; // Compare each character until a mismatch is found or both strings end while (str1[i] == str2[i] && str1[i] != '\0') { i++; } // Return the difference between the mismatched characters return str1[i] - str2[i]; } int main() { const char str1[] = "Hello"; const char str2[] = "World"; // Compare str1 and str2 and print the result int result = compareStrings(str1, str2); printf("Comparison Result: %d\n", result); return 0; }Substring Search:
#include <stdio.h> // Function to search for a substring in a string int searchSubstring(const char *str, const char *substring) { int i, j; // Iterate through the string for (i = 0; str[i] != '\0'; i++) { // Check for substring match starting from the current position for (j = 0; substring[j] != '\0' && str[i + j] == substring[j]; j++); // If the entire substring is found, return the starting position if (substring[j] == '\0') { return i; } } // Return -1 if substring is not found return -1; } int main() { const char str[] = "Hello, World!"; const char substring[] = "World"; // Search for the substring and print the result int position = searchSubstring(str, substring); if (position != -1) { printf("Substring found at position: %d\n", position); } else { printf("Substring not found.\n"); } return 0; }Palindrome Check:
#include <stdio.h> #include <stdbool.h> // Function to check if a string is a palindrome bool isPalindrome(const char *str) { int length = stringLength(str); int i, j; // Compare characters from the beginning and end of the string for (i = 0, j = length - 1; i < j; i++, j--) { if (str[i] != str[j]) { return false; } } // If the loop completes without returning, the string is a palindrome return true; } int main() { const char str[] = "radar"; // Check if the string is a palindrome and print the result if (isPalindrome(str)) { printf("%s is a palindrome.\n", str); } else { printf("%s is not a palindrome.\n", str); } return 0; }Count Vowels and Consonants:
#include <stdio.h> // Function to count vowels and consonants in a string void countVowelsConsonants(const char *str, int *vowels, int *consonants) { *vowels = 0; *consonants = 0; // Iterate through the string and classify each character for (int i = 0; str[i] != '\0'; i++) { char ch = str[i]; // Check if the character is a vowel if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') { (*vowels)++; } else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { // Check if the character is a consonant (*consonants)++; } } } int main() { const char str[] = "Hello, World!"; int numVowels, numConsonants; // Count vowels and consonants and print the result countVowelsConsonants(str, &numVowels, &numConsonants); printf("Vowels: %
d\nConsonants: %d\n", numVowels, numConsonants);
return 0; }
8. **String Tokenization:**
```c
#include <stdio.h>
#include <string.h>
// Function to tokenize a string
void tokenizeString(const char *sentence) {
char copy[100];
strcpy(copy, sentence);
// Tokenize the string using strtok
char *token = strtok(copy, " ");
// Iterate through tokens and print each one
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, " ");
}
}
int main() {
const char sentence[] = "This is a sample sentence.";
// Tokenize the sentence and print each word
tokenizeString(sentence);
return 0;
}
String Compression:
#include <stdio.h> // Function to compress a string void compressString(char *str) { int length = stringLength(str); int compressedIndex = 0; // Iterate through the string to compress for (int i = 0; i < length; i++) { char currentChar = str[i]; int count = 1; // Count consecutive occurrences of the current character while (i + 1 < length && str[i + 1] == currentChar) { i++; count++; } // Append the compressed character and count to the result string str[compressedIndex++] = currentChar; if (count > 1) { // Only append the count if it is greater than 1 str[compressedIndex++] = count + '0'; } } // Add null terminator to the end of the compressed string str[compressedIndex] = '\0'; } int main() { char str[] = "aaabbbcc"; // Compress the string and print the result compressString(str); printf("Compressed String: %s\n", str); return 0; }Remove Duplicates:
#include <stdio.h> // Function to remove duplicate characters from a string void removeDuplicates(char *str) { int hash[256] = {0}; // Assuming ASCII characters int i, j = 0; // Iterate through the string for (i = 0; str[i] != '\0'; i++) { // Check if the character has been encountered before if (hash[str[i]] == 0) { // If not, mark it as encountered and copy it to the result string hash[str[i]] = 1; str[j++] = str[i]; } } // Add null terminator to the end of the modified string str[j] = '\0'; } int main() { char str[] = "programming"; // Remove duplicates from the string and print the result removeDuplicates(str); printf("String after removing duplicates: %s\n", str); return 0; }