-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathreplace_character.c
More file actions
93 lines (78 loc) · 2.69 KB
/
Copy pathreplace_character.c
File metadata and controls
93 lines (78 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
* Program: Character Replacement
* Description: Replaces all occurrences of a character with another in a string
* Author: Amey Thakur
* Reference: https://github.com/Amey-Thakur/DATA-STRUCTURES-AND-DATA-STRUCTURES-LAB
*/
#include <stdio.h>
#include <conio.h>
#define MAX_LENGTH 100 // Maximum string length
// Function prototypes
void replaceCharacter(char* str, char oldChar, char newChar);
void displayResults(char* original, char* modified, char oldChar, char newChar, int count);
int main() {
char str[MAX_LENGTH]; // Input string
char oldChar; // Character to be replaced
char newChar; // Replacement character
char originalCopy[MAX_LENGTH]; // Copy of original string
int i, count = 0;
// Read input string
printf("Enter a string: ");
fgets(str, MAX_LENGTH, stdin);
str[strcspn(str, "\n")] = '\0'; // Remove newline
// Save original string for display
strcpy(originalCopy, str);
// Read character to be replaced
printf("Enter the character to be replaced: ");
scanf("%c", &oldChar);
// Read replacement character
printf("Enter the replacement character: ");
scanf(" %c", &newChar); // Space before %c to skip whitespace
// Count occurrences before replacement
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == oldChar) {
count++;
}
}
// Perform replacement
replaceCharacter(str, oldChar, newChar);
// Display results
displayResults(originalCopy, str, oldChar, newChar, count);
getch();
return 0;
}
/*
* Function: replaceCharacter
* Description: Replaces all occurrences of oldChar with newChar in string
* Parameters:
* str - String to modify
* oldChar - Character to be replaced
* newChar - Replacement character
*/
void replaceCharacter(char* str, char oldChar, char newChar) {
int i = 0;
// Traverse string and replace characters
while (str[i] != '\0') {
if (str[i] == oldChar) {
str[i] = newChar;
}
i++;
}
}
/*
* Function: displayResults
* Description: Displays original and modified strings
* Parameters:
* original - Original string
* modified - Modified string after replacement
* oldChar - Character that was replaced
* newChar - Replacement character
* count - Number of replacements made
*/
void displayResults(char* original, char* modified, char oldChar, char newChar, int count) {
printf("\n--- Results ---\n");
printf("Original string: \"%s\"\n", original);
printf("Modified string: \"%s\"\n", modified);
printf("\nReplaced '%c' with '%c'\n", oldChar, newChar);
printf("Total replacements: %d\n", count);
}