-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem16.c
More file actions
95 lines (79 loc) Β· 2.34 KB
/
Copy pathproblem16.c
File metadata and controls
95 lines (79 loc) Β· 2.34 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
94
95
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// Function to reverse characters in a string between given indices
void reverse(char *str, int start, int end) {
while (start < end) {
char temp = str[start];
str[start++] = str[end];
str[end--] = temp;
}
}
// This function removes leading, trailing, and extra spaces
char *cleanSpaces(char *str) {
int i = 0, j = 0;
// Skip initial spaces
while (str[i] && isspace(str[i])) i++;
while (str[i]) {
if (!isspace(str[i])) {
str[j++] = str[i++];
} else {
// Replace multiple spaces with a single one
str[j++] = ' ';
while (isspace(str[i])) i++;
}
}
// Remove trailing space if any
if (j > 0 && str[j - 1] == ' ') j--;
str[j] = '\0';
return str;
}
// This function reverses each word and then the whole sentence
void reverseWords(char *sentence) {
cleanSpaces(sentence); // Step 1: Clean unnecessary spaces
int len = strlen(sentence);
// Step 2: Reverse the entire cleaned sentence
reverse(sentence, 0, len - 1);
// Step 3: Reverse each individual word
int start = 0;
for (int end = 0; end <= len; end++) {
if (sentence[end] == ' ' || sentence[end] == '\0') {
reverse(sentence, start, end - 1);
start = end + 1;
}
}
}
// Dynamically reads a line of input from the user
char *getInputLine() {
int capacity = 100, size = 0;
char *line = (char *)malloc(capacity * sizeof(char));
if (!line) {
printf("β Memory allocation failed.\n");
exit(1);
}
char ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
if (size >= capacity - 1) {
capacity *= 2;
char *temp = realloc(line, capacity);
if (!temp) {
free(line);
printf("β Memory reallocation failed.\n");
exit(1);
}
line = temp;
}
line[size++] = ch;
}
line[size] = '\0';
return line;
}
int main() {
printf("π£οΈ Enter Anubhav's sentence: ");
char *speechLine = getInputLine();
reverseWords(speechLine);
printf("β
Final cleaned-up sentence:\n%s\n", speechLine);
free(speechLine); // Don't forget to release allocated memory!
return 0;
}