Answer to Question #75913 in C for Muhammad

Question #75913
In the main function, input one string and pass it to a function named cleanString. This function removes the non-alphabetic characters and writes the rest into a new character array (i.e. non-alphabetic characters are +, - ?, *, 1,2,3,…). After receiving a cleaned array, you should call another function named reverseWords. This function takes and returns the string as a parameter. String should be arranged in a reversed order for each word. All operations in this function should take place on the same string, you shouldn’t be using a temporary array for the reverse operation. Finally, print the result in the main function.

Sample run:

Enter first string: This-?=*is__12the**23%third?[]homework--_?().

Cleaned string: This is the third homework

Reversed string: sihT si eht driht krowemoh
1
Expert's answer
2018-04-12T15:31:10-0400
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

#define MAX_LINE 4096


char* cleanString(const char* s) {
int len = 0, i = 0;
char* result = NULL;
const char* ptr = s;
while (*(ptr + len) != '\0') ++len;

result = (char*)malloc(sizeof(char) * (len + 1));
ptr = s;
i = 0;
while (*ptr != '\0') {
if((*ptr >= 'a' && *ptr <= 'z')
|| (*ptr >= 'A' && *ptr <= 'Z')) {
result[i++] = *ptr;
}
else if (i > 0 && result[i - 1] != ' ') {
result[i++] = ' ';
}
++ptr;
}
if (i > 0 && result[i - 1] == ' ') i--;
result[i] = '\0';
return result;
}

char* reverseWords(char* s) {
int i = 0, j = 0, k = 0, len;
char temp;

while (s[i] != '\0') {
// Find word separator
len = 0;
k = i;
while (s[i] != '\0' && s[i] != ' ') {
++i;
++len;
}

// Reverse word
--i;
for (j = 0; j < len / 2; ++j) {
temp = s[k + j];
s[k + j] = s[i - j];
s[i - j] = temp;
}

// Find next non space character
if (s[i] != '\0') {
i++;
while (s[i] != '\0' && s[i] == ' ') ++i;
}
}
return s;
}


int main(int argc, char *argv[]) {
char str[MAX_LINE] = { 0 };
char* cleaned = NULL, *reversed = NULL;
printf("Enter first string: ");
scanf("%s", str);

cleaned = cleanString(str);
printf("Cleaned string: %s\n", cleaned);

reversed = reverseWords(cleaned);
printf("Reversed string: %s\n", reversed);

free(cleaned);

return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS