Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Longest Word C++
    I can't find the mistake,If anyone can help me understand what I am doing wrong, your assistance will be greatly appreciated.
    string LongestWord(string sen) {
    
      // code goes here
      int n=0;
      string abc,maxing;
      for(int i=0;i<sen.length();i++)
      {
            if((sen[i]<'a'||sen[i]>'z')&&(sen[i]<'A'||sen[i]>'Z'))
          {
              if(abc.length()>maxing.length())
                maxing=abc;
              abc.clear();
              continue;
          }
            abc+=sen[i];
      }
      if(maxing.length() < abc.length())maxing=abc;
      return maxing;
    
    }
    
    cloudshadow posted this question on 4/27/14 | cpp, longest, word
    Answers
  • +
  • 2
  • -
  • The code is absolutely fine. it works well.
    #include <iostream>
    
    using namespace std;
    string LongestWord(string sen) {
    
      // code goes here
      int n=0;
      string abc,maxing;
      for(int i=0;i<sen.length();i++)
      {
            if((sen[i]<'a'||sen[i]>'z')&&(sen[i]<'A'||sen[i]>'Z'))
          {
              if(abc.length()>maxing.length())
                maxing=abc;
              abc.clear();
              continue;
          }
            abc+=sen[i];
      }
      if(maxing.length() < abc.length())maxing=abc;
      return maxing;
    
    }
    int main()
    {
       cout << LongestWord("subahsh is a good fgdsfgdfgdfg boy");
       
       return 0;
    }
    
  • +
  • 2
  • -
  • Just a piece of information for your future coding challenges: the c and c++ stdlib have a function
     int isalpha(int c)
    which tells you precisely what you want to check. www.cplusplus.com/reference/cctype/isalpha/
  • +
  • 1
  • -
  • thank you so much.I find the reason of mistake,the wrong is that i don't consider numbers. especially thank mike0809 ,i have learned a lot from you.
  • +
  • 0
  • -
  • won't thins break for words such as don't, won't,etc such as don't do that - would return that, however it has to return don't. The requriement is to ignore punctuations only for the length right and not strip of the punctuations from the word totally
  • +
  • 0
  • -
  • If you want to consider ONLY alphabets, use
    if(isalpha(c))
    If you want to consider ONLY numbers, use
    if(isdigit(c))
    If you want to consider BOTH alphabets and numbers, use
    if(isalnum(c))
    where
    c
    is a char data type
  • +
  • 0
  • -
  • Some symbol can't be less than 'A' and more than 'z' in the same time. You should check for alphabet in if condition and other symbols in else.
    Log in to write an answer.