1. /**
  2. * A program to satisfy the unfair requirements of my
  3. * teacher to not use the string class and do a couple of
  4. * string operations on a sentence
  5. */
  6. #include<iostream>
  7. #include<string>
  8. using namespace std;
  9. int countWords(const char* sent)
  10. {
  11. int count = 0;
  12. while(*sent != '\0')
  13. {
  14. if(*sent == ' ') count++;
  15. *sent++;
  16. }
  17. return count+1;
  18. }
  19. string longest(string words[], int length)
  20. {
  21. string longestWord = "";
  22. for(int i = 0; i < length; i++)
  23. {
  24. if(longestWord.length() < words[i].length())
  25. {
  26. longestWord = words[i];
  27. }
  28. }
  29. return longestWord;
  30. }
  31. int getWordSum(string st)
  32. {
  33. int sum = 0;
  34. const char* chr = st.c_str(); /** I have used strings here */
  35. while(*chr != '\0')
  36. {
  37. sum += *chr;
  38. *chr++;
  39. }
  40. return sum;
  41. }
  42. int main()
  43. {
  44. char* sent = new char[1024];
  45. cout<<"Enter a sentence:";
  46. cin.get(sent, 1024, '\n');
  47. int wordcount = countWords(sent);
  48. string words[wordcount];// = new char[wordcount][20];
  49. char* tok = strtok(sent, " ");
  50. //tokenize and count
  51. int i = 0;
  52. while(tok != NULL)
  53. {
  54. cout<<tok<<"\n";
  55. words[i] = tok;
  56. i++;
  57. tok = strtok(NULL, " ");
  58. }
  59. cout<<"No. of words = "<<i<<"\n";
  60. //display longest
  61. cout<<"The longest word is:"<<longest(words, i)<<"\n";
  62. //sort and display words
  63. int wordValues[wordcount];
  64. for(int j = 0; j < wordcount; j++)
  65. {
  66. wordValues[j] = getWordSum(words[j]);
  67. }
  68. //sort
  69. int smallest = 0;
  70. cout<<"HI\n";
  71. for(int k = 0; k<wordcount-1; k++)
  72. {
  73. smallest = k;
  74. cout<<"xeced";
  75. for(int l = k+1; l<wordcount;l++)
  76. {
  77. if(wordValues[l] < wordValues[smallest])
  78. smallest = l;
  79. }
  80. string tmp = words[smallest];
  81. words[smallest] = words[k];
  82. words[k] = tmp;
  83. int tmpV = wordValues[smallest];
  84. wordValues[smallest] = wordValues[k];
  85. wordValues[k] = tmpV;
  86. }
  87. cout<<"Words in ascending order:\n";
  88. for(int j = 0; j<wordcount; j++)
  89. cout<<words[j]<<endl;
  90. //frequency
  91. for(int x = 0; x < wordcount; x++)
  92. {
  93. int count = 1;
  94. for(int y = x+1; y < wordcount; y++)
  95. {
  96. if(words[x] == words[y] && !(words[x] == "\0"))
  97. {
  98. count++;
  99. words[y] = "\0";
  100. }
  101. }
  102. cout<<"Frequency of "<<words[x]<<":"<<count<<endl;
  103. }
  104. return 0;
  105. }