Write a C program to eliminate white spaces from the given string.
#include <stdio.h>
#include <string.h>
int main() {
char str[256], *ptr1, *ptr2;
/* get the input string from the user */
printf("Enter your input string:");
fgets(str, 256, stdin);
str[strlen(str) - 1] = '\0';
/* ptr1 and ptr2 points to 1st character of i/p string */
ptr1 = ptr2 = str;
/* copy all characters in the i/p string except space */
while (*ptr1 != '\0') {
/* skip the space */
if (*ptr1 == ' ') {
ptr1++;
continue;
}
/* copy characters alone */
*ptr2++ = *ptr1++;
}
/* null termination */
*ptr2 = *ptr1;
/* printing the result */
printf("Resultant String: %s\n", str);
return 0;
}
#include <string.h>
int main() {
char str[256], *ptr1, *ptr2;
/* get the input string from the user */
printf("Enter your input string:");
fgets(str, 256, stdin);
str[strlen(str) - 1] = '\0';
/* ptr1 and ptr2 points to 1st character of i/p string */
ptr1 = ptr2 = str;
/* copy all characters in the i/p string except space */
while (*ptr1 != '\0') {
/* skip the space */
if (*ptr1 == ' ') {
ptr1++;
continue;
}
/* copy characters alone */
*ptr2++ = *ptr1++;
}
/* null termination */
*ptr2 = *ptr1;
/* printing the result */
printf("Resultant String: %s\n", str);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input string:ignore white space in input string
Resultant String: ignorewhitespaceininputstring
Enter your input string:ignore white space in input string
Resultant String: ignorewhitespaceininputstring
No comments:
Post a Comment