0% found this document useful (0 votes)
1 views14 pages

String Programs

Uploaded by

spindia0312
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views14 pages

String Programs

Uploaded by

spindia0312
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

String Length Calculation Program

Detailed Explanation:

This program demonstrates how to calculate the length of a string without using the built-
in strlen() function. Strings in C are character arrays terminated by a null character ('\0').

#include <stdio.h>

#include <string.h>

// Custom function to calculate string length

int string_length(char str[]) {

int length = 0;

// Iterate through each character until null terminator is found

while (str[length] != '\0') {

length++;

return length;

int main() {

char str[] = "Hello World";

printf("String: %s\n", str);

printf("Length using custom function: %d\n", string_length(str));

printf("Length using built-in strlen: %lu\n", strlen(str));

return 0;

Input/Output:

String: Hello World

Length using custom function: 11

Length using built-in strlen: 11

Key Concepts:
• Null Terminator: Strings in C must end with '\0'

• Array Traversal: We iterate through the array until we find the null terminator

• Time Complexity: O(n) where n is the string length

• Space Complexity: O(1) as we only use one counter variable

2. String Copy Implementation

Detailed Explanation:

This program shows how to copy one string to another without using strcpy(). Understanding string
copying is fundamental for memory management in C.

#include <stdio.h>

// Custom string copy function

void string_copy(char dest[], char src[]) {

int i = 0;

// Copy each character from source to destination

while (src[i] != '\0') {

dest[i] = src[i];

i++;

// Don't forget to add the null terminator

dest[i] = '\0';

int main() {

char source[] = "Programming";

char destination[50]; // Ensure destination has enough space

printf("Before copying:\n");

printf("Source: %s\n", source);

printf("Destination: %s\n", destination); // Will contain garbage values


string_copy(destination, source);

printf("\nAfter copying:\n");

printf("Source: %s\n", source);

printf("Destination: %s\n", destination);

return 0;

Input/Output:

Before copying:

Source: Programming

Destination: �↨@ // Garbage values

After copying:

Source: Programming

Destination: Programming

Key Concepts:

• Memory Safety: Ensure destination array has sufficient space

• Null Terminator: Crucial to add '\0' at the end

• Character-by-Character Copy: Manual iteration through the array

• Buffer Overflow Risk: Without proper bounds checking, this can cause issues

3. Linear Search in String

Detailed Explanation:

Linear search is the simplest searching algorithm that checks each element sequentially until the
target is found or the end is reached.

#include <stdio.h>

int linear_search(char str[], char key) {


// Iterate through each character in the string

for (int i = 0; str[i] != '\0'; i++) {

// Check if current character matches the key

if (str[i] == key) {

return i; // Return position if found

return -1; // Return -1 if not found

int main() {

char str[] = "algorithm";

char key = 'r';

printf("Searching for character '%c' in string: %s\n", key, str);

int position = linear_search(str, key);

if (position != -1) {

printf("Character '%c' found at position %d\n", key, position);

printf("String visualization: ");

for (int i = 0; str[i] != '\0'; i++) {

if (i == position) {

printf("[%c] ", str[i]); // Highlight found character

} else {

printf("%c ", str[i]);

printf("\n");

} else {

printf("Character '%c' not found in the string\n", key);


}

return 0;

Input/Output:

Searching for character 'r' in string: algorithm

Character 'r' found at position 3

String visualization: a l g [r] i t h m

Key Concepts:

• Sequential Search: Checks each element one by one

• Time Complexity:

o Best case: O(1) - element at first position

o Worst case: O(n) - element at last position or not present

o Average case: O(n)

• Space Complexity: O(1)

• Use Case: Suitable for small arrays or unsorted data

4. Pattern Matching (Naive Algorithm)

Detailed Explanation:

The naive pattern matching algorithm slides the pattern over the text and checks for matches at
each position. It's simple but not the most efficient.

#include <stdio.h>

#include <string.h>

void pattern_search(char text[], char pattern[]) {

int n = strlen(text); // Length of main text

int m = strlen(pattern); // Length of pattern to search

printf("Text: %s (Length: %d)\n", text, n);


printf("Pattern: %s (Length: %d)\n", pattern, m);

printf("Pattern found at positions: ");

int found = 0;

// Slide pattern over text

for (int i = 0; i <= n - m; i++) {

int j;

// Check for pattern match at current position

for (j = 0; j < m; j++) {

if (text[i + j] != pattern[j]) {

break; // Mismatch found, break inner loop

// If inner loop completed, pattern found

if (j == m) {

printf("%d ", i);

found++;

if (found == 0) {

printf("None");

printf("\nTotal occurrences: %d\n", found);

int main() {

char text[] = "ABABDABACDABABCABAB";


char pattern[] = "ABAB";

pattern_search(text, pattern);

// Additional example

printf("\n--- Additional Example ---\n");

char text2[] = "hello hello world hello";

char pattern2[] = "hello";

pattern_search(text2, pattern2);

return 0;

Input/Output:

Text: ABABDABACDABABCABAB (Length: 19)

Pattern: ABAB (Length: 4)

Pattern found at positions: 0 10 15

Total occurrences: 3

--- Additional Example ---

Text: hello hello world hello (Length: 23)

Pattern: hello (Length: 5)

Pattern found at positions: 0 6 18

Total occurrences: 3

Key Concepts:

• Brute Force Approach: Checks all possible positions

• Time Complexity: O((n-m+1) * m) where n=text length, m=pattern length

• Space Complexity: O(1)

• Inefficiency: Re-checks characters multiple times

• Best for: Small patterns or texts


5. String Reversal Algorithm

Detailed Explanation:

This algorithm reverses a string in-place using two pointers - one starting from the beginning and
one from the end, swapping characters until they meet.

#include <stdio.h>

#include <string.h>

void reverse_string(char str[]) {

int length = strlen(str);

int start = 0; // Left pointer

int end = length - 1; // Right pointer

printf("Reversal process:\n");

printf("Initial: %s\n", str);

// Swap characters from both ends towards center

while (start < end) {

// Swap characters at start and end positions

char temp = str[start];

str[start] = str[end];

str[end] = temp;

// Visualize the process

printf("Step %d: ", start + 1);

for (int i = 0; i < length; i++) {

if (i == start || i == end) {

printf("[%c] ", str[i]);

} else {

printf("%c ", str[i]);

}
}

printf("\n");

// Move pointers towards center

start++;

end--;

int main() {

char str[] = "Hello World";

printf("Original string: %s\n", str);

printf("String length: %lu\n\n", strlen(str));

reverse_string(str);

printf("\nFinal reversed string: %s\n", str);

return 0;

Input/Output:

Original string: Hello World

String length: 11

Reversal process:

Initial: Hello World

Step 1: [d] e l l o W o r l [H]

Step 2: d [l] l l o W o r [o] H

Step 3: d l [r] l o W o [l] o H


Step 4: d l r [o] o W [l] l o H

Step 5: d l r o [ ] [W] o l l o H

Step 6: d l r o [o] [ ] W l l o H

Final reversed string: dlroW olleH

Key Concepts:

• In-place Algorithm: Modifies the original array without extra space

• Two-pointer Technique: Efficient approach for symmetric operations

• Time Complexity: O(n/2) = O(n)

• Space Complexity: O(1)

• Swap Operation: Temporary variable needed for character exchange

6. Palindrome Checker

Detailed Explanation:

A palindrome is a string that reads the same forwards and backwards. This program checks for
palindromes while handling case sensitivity.

#include <stdio.h>

#include <string.h>

#include <ctype.h>

int is_palindrome(char str[]) {

int left = 0;

int right = strlen(str) - 1;

printf("Checking palindrome: %s\n", str);

printf("Comparison process:\n");

while (left < right) {

// Convert to lowercase for case-insensitive comparison

char left_char = tolower(str[left]);


char right_char = tolower(str[right]);

printf(" Comparing '%c' (position %d) with '%c' (position %d): ",

str[left], left, str[right], right);

if (left_char != right_char) {

printf("NOT EQUAL - Not a palindrome\n");

return 0;

printf("EQUAL - Continue\n");

left++;

right--;

return 1;

void analyze_palindrome(char str[]) {

printf("\nAnalyzing: '%s'\n", str);

printf("Length: %lu\n", strlen(str));

if (is_palindrome(str)) {

printf("✓ '%s' IS a palindrome\n", str);

} else {

printf("✗ '%s' is NOT a palindrome\n", str);

printf("----------------------------------------\n");

int main() {

// Test various strings


char str1[] = "Madam";

char str2[] = "Hello";

char str3[] = "racecar";

char str4[] = "A man a plan a canal Panama";

analyze_palindrome(str1);

analyze_palindrome(str2);

analyze_palindrome(str3);

// For phrases with spaces, we need a more advanced function

printf("Note: Advanced palindrome check needed for phrases with spaces\n");

return 0;

Input/Output:

Analyzing: 'Madam'

Length: 5

Checking palindrome: Madam

Comparison process:

Comparing 'M' (position 0) with 'm' (position 4): EQUAL - Continue

Comparing 'a' (position 1) with 'a' (position 3): EQUAL - Continue

✓ 'Madam' IS a palindrome

----------------------------------------

Analyzing: 'Hello'

Length: 5

Checking palindrome: Hello

Comparison process:

Comparing 'H' (position 0) with 'o' (position 4): NOT EQUAL - Not a palindrome

✗ 'Hello' is NOT a palindrome


----------------------------------------

Analyzing: 'racecar'

Length: 7

Checking palindrome: racecar

Comparison process:

Comparing 'r' (position 0) with 'r' (position 6): EQUAL - Continue

Comparing 'a' (position 1) with 'a' (position 5): EQUAL - Continue

Comparing 'c' (position 2) with 'c' (position 4): EQUAL - Continue

✓ 'racecar' IS a palindrome

----------------------------------------

Note: Advanced palindrome check needed for phrases with spaces

Key Concepts:

• Palindrome Definition: String that reads same forwards and backwards

• Case Insensitivity: Use tolower() or toupper() for fair comparison

• Two-pointer Approach: Compare characters from both ends

• Time Complexity: O(n/2) = O(n)

• Space Complexity: O(1)

Time
Time Complexity Time Complexity Space
Algorithm Complexity
(Average) (Worst) Complexity
(Best)

Bubble
O(n) O(n²) O(n²) O(1)
Sort

Selection
O(n²) O(n²) O(n²) O(1)
Sort
Time
Time Complexity Time Complexity Space
Algorithm Complexity
(Average) (Worst) Complexity
(Best)

Insertion
O(n) O(n²) O(n²) O(1)
Sort

Merge Sort O(n log n) O(n log n) O(n log n) O(n)

Quick Sort O(n log n) O(n log n) O(n²) O(log n)

Heap Sort O(n log n) O(n log n) O(n log n) O(1)

You might also like