Advertisement
Guest User

Untitled

a guest
Feb 16th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. //checks if two words are anagrams. returns 0 if yes, 1 if not an anagram. assumes 2 inputs
  2. //without any whitespace characters
  3.  
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <ctype.h>
  7.  
  8. void bubble_sort(char [], int);
  9. void lowercase(char [], int);
  10.  
  11. int main (int argc, char *argv[]) {
  12.  
  13. int len1 = strlen(argv[1]);
  14. int len2 = strlen(argv[2]);
  15.  
  16. if (len1 != len2) return 1; //return 1 if the lengths are not equal (not an anagram)
  17. else {
  18.  
  19. //convert all letters to lowercase
  20. lowercase(argv[1], len1);
  21. lowercase(argv[2], len2);
  22.  
  23. //sort arrays using bubble sort
  24. bubble_sort(argv[1], len1);
  25. bubble_sort(argv[2], len2);
  26.  
  27. if (strcmp(argv[1], argv[2]) == 0) return 0; //anagram if two sorted strings are equal
  28. else return 1; //not an anagram if not
  29. }
  30. }
  31.  
  32. void bubble_sort(char array[], int len) {
  33. //sorts an array using bubble sort (in ascending order)
  34.  
  35. for (int i = 0; i < len-1; i++) {
  36. for(int j = 0; j < len-1-i; j++) {
  37. if (array[j] > array[j+1]) {
  38.  
  39. //swap array[j] and array[j+1]
  40.  
  41. char temp = array[j];
  42. array[j] = array[j+1];
  43. array[j+1] = temp;
  44. }
  45. }
  46. }
  47. }
  48.  
  49. void lowercase(char string[], int len) {
  50. //takes a given string of length len and converts all letters
  51. // into lowercase (upto 100 non-whitespace chars)
  52.  
  53. for (int i = 0; i < len; i++) {
  54. if (isalpha(string[i])) {
  55. string[i] = tolower(string[i]);
  56. }
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement