Advertisement
Guest User

Untitled

a guest
Mar 19th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <array>
  5.  
  6. using namespace std;
  7.  
  8. //Exercise 7.28
  9. string noSpaces(string str)
  10. {
  11.     int len = str.length();
  12.  
  13.     for(int i{0}; i < len; ++i)
  14.     {
  15.         if(str[i] == ' ')
  16.         {
  17.             str.erase(i,1);
  18.         }
  19.     }
  20.     return str;
  21. }
  22.  
  23. bool testPalindrome(string str)
  24. {
  25.     bool result{false};
  26.     str = noSpaces(str);
  27.  
  28.     if(str.length() == 1)
  29.     {
  30.         result = true;
  31.     }
  32.     else if(str.length() == 2)
  33.     {
  34.         result = false;
  35.     }
  36.     else
  37.     {
  38.         if(str[0] == str[str.length() - 1]) //if the first and last char are the same
  39.         {
  40.             string newString{str.substr(1, str.length() - 2)};
  41.             result = testPalindrome(newString);
  42.         }
  43.         else
  44.         {
  45.             result = false;
  46.         }
  47.     }
  48.  
  49.     return result;
  50. }
  51.  
  52.  
  53. //Exercise 7.31
  54. //Not sure how to do this with a void function, will probably come back to it.
  55. string stringReverse(string word, size_t subscript = 0)
  56. {
  57.     string initialString{word.substr(subscript, word.length())};
  58.     string reverseString{};
  59.  
  60.     if(initialString.length() == 1)
  61.     {
  62.         reverseString = initialString;
  63.     }
  64.     else
  65.     {
  66.         size_t stringSize{initialString.length()};
  67.         string newString{initialString.substr(subscript,stringSize - 1)};
  68.  
  69.         reverseString = (initialString[stringSize - 1]) + stringReverse(newString, subscript);
  70.     }
  71.  
  72.     return reverseString;
  73. }
  74.  
  75.  
  76. int main() {
  77.     //Exercise 7.28
  78.     cout << testPalindrome("a man a plan a canal panama") << endl;
  79.     cout << testPalindrome("race car") << endl;
  80.     cout << testPalindrome("not a palindrome") << endl;
  81.  
  82.     //Exercise 7.31
  83.     cout << stringReverse("wyatt");
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement