Friday, July 4, 2025

๐Ÿš€ DSA with C – Day 5: Strings in C


๐ŸŽฏ Goal:


๐Ÿง  What is a String in C?

A string is a character array ending with a null character (\0).

๐Ÿ”ง Declaration


char str[100]; // Character array

๐Ÿ“ฅ Input


scanf("%s", str); // No spaces fgets(str, sizeof(str), stdin); // With spaces

๐Ÿ‘จ‍๐Ÿ’ป 1. Reverse a String


#include <stdio.h> #include <string.h> int main() { char str[100]; printf("Enter a string: "); scanf("%s", str); // Use fgets if you want spaces int len = strlen(str); for (int i = 0; i < len / 2; i++) { char temp = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = temp; } printf("Reversed string: %s\n", str); return 0; }

๐Ÿ‘จ‍๐Ÿ’ป 2. Check if a String is a Palindrome


#include <stdio.h> #include <string.h> int main() { char str[100]; int flag = 1; printf("Enter a string: "); scanf("%s", str); int len = strlen(str); for (int i = 0; i < len / 2; i++) { if (str[i] != str[len - i - 1]) { flag = 0; break; } } if (flag) printf("Palindrome\n"); else printf("Not a palindrome\n"); return 0; }

๐Ÿ‘จ‍๐Ÿ’ป 3. Character Frequency Count


#include <stdio.h> #include <string.h> int main() { char str[100]; int freq[256] = {0}; // ASCII chars printf("Enter a string: "); scanf("%s", str); for (int i = 0; str[i] != '\0'; i++) { freq[(int)str[i]]++; } printf("Character frequencies:\n"); for (int i = 0; i < 256; i++) { if (freq[i] > 0) printf("%c: %d\n", i, freq[i]); } return 0; }

๐Ÿ‘จ‍๐Ÿ’ป 4. Check if Two Strings Are Anagrams

Two strings are anagrams if they contain the same characters in any order.


#include <stdio.h> #include <string.h> int isAnagram(char str1[], char str2[]) { int count[256] = {0}; if (strlen(str1) != strlen(str2)) return 0; for (int i = 0; str1[i]; i++) { count[(int)str1[i]]++; count[(int)str2[i]]--; } for (int i = 0; i < 256; i++) { if (count[i] != 0) return 0; } return 1; } int main() { char str1[100], str2[100]; printf("Enter two strings: "); scanf("%s %s", str1, str2); if (isAnagram(str1, str2)) printf("Anagram\n"); else printf("Not anagram\n"); return 0; }

๐Ÿงช Practice Problems:

  1. Count vowels and consonants in a string.

  2. Convert lowercase letters to uppercase.

  3. Remove duplicate characters from a string.

  4. Check if two strings are rotations of each other (e.g., abc and cab).


๐Ÿ“˜ Homework for Day 5:

  • Implement your own versions of:

    • strlen()

    • strcpy()

    • strcmp()

  • Try a string problem from LeetCode: Valid Anagram

No comments:

Post a Comment

How we can get higher marks in semester exam

 Here we talk about how to get higher marks in exams or test paper. Now we have to remember that the test and exams are follow the pattern b...