Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- //remove redundant spaces in a string s
- void removeRedSpaces(char s[]) {
- int n, low, up, i, j; char x[100];
- n = strlen(s);
- i = 0; j = n - 1;
- while(i < n && s[i] == ' ') i++;
- low = i;
- while(j > 0 && s[j] == ' ') j--;
- up = j;
- if(low > up) {
- strcpy(s, "");
- return;
- }
- strcpy(x, "");
- i = low; j = 0;
- while(i <= up) {
- while(i < up && s[i] == ' ') i++;
- while(i <= up && s[i] != ' ') x[j++] = s[i++];
- if(i <= up) x[j++] = ' ';
- }
- x[j] = '\0';
- strcpy(s,x);
- }
- void split( char s[], char out[][30], int &length) //tach cac tu trong 1 chuoi
- {
- removeRedSpaces(s);
- int i = 0, j, k = 0;
- while ( i < strlen(s))
- {
- for ( j = i; s[j] != '\0' && s[j] != ' '; j ++)
- out[ k ][ j - i ] = s[j];
- out[ k ][ j - i ] = '\0';
- i = j + 1;
- k++;
- }
- length = k;
- }
- //Enter data for a string s
- void input(char s[]) {
- printf("Enter a string s = ");
- fflush(stdin);
- gets(s);
- }
- //Display a string s
- void display(char s[]) {
- printf("%s\n",s);
- }
- void fun(char s[]) {
- int i, j, n;
- char x[100][30], temp[30];
- split(s, x, n);
- for (i = n - 5; i < n ; i++)
- for (j = i + 1; j < n; j++)
- if (strcmp(x[i],x[j]) > 0)
- { //doi cho
- strcpy(temp,x[i]);
- strcpy(x[i],x[j]);
- strcpy(x[j],temp);
- }
- // rebuild
- int length = strlen(s);
- strcpy(s, "");
- for (i = 0; i < n; ++i) {
- strcat(s, x[i]);
- strcat(s, " ");
- }
- s[length] = '\0';
- }
- int main()
- {
- system("cls");
- printf("\nTEST Q5 (2 marks):\n");
- char s[100];
- input(s);
- printf("\nThe original string:\n");
- display(s);
- printf("\nThe string after processing:\n");
- fun(s);
- display(s);
- //==THE OUTPUT AFTER THIS LINE WILL BE USED TO MARK YOUR PROGRAM==
- printf("\nOUTPUT:\n");
- display(s);
- printf("\n");
- system ("pause");
- return(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement