开发者

Sort the sentence based on the word length

I am newbie programmer C/C++. Was learning pointers and character pointers and was trying to solve an exercise problem. Problem statement

Given a sentence " World is a great place to live in"

Problem description: Rearrange the given sentence based on the ascending order of its word length

output should be " A is in to live world great place"

I am trying my best and am pasting the code that I wrote, but not able to arrive at the answer. Can somebody point out the errors. I am sure there are lots.

#include <iostream>    
#include <string.h>

using namespace std;
char* breakIntoWords(char *,char*pt);

    int getwordcount(char* p)
    {
     int wc = 0;

     while(*p == ' ')
      {
         p++;
      }
      while( 1) {

      while( *p != ' ' && *p != '\0' && *p !='\n')
      { 
        p++;

      }
    if(*p ==  ' ')
    {
       p++;
    }
    else{
       break;
    }


      wc++;
      }
    wc++;
      return wc;

    }

    int main()
    {

       char bsentence[120][5];
       char sentence[120];
        cout<<"Ent&am开发者_StackOverflowp;er STring"<<endl;
        char *p ;
        p = "Test it again and welcome";
        strcpy(sentence, p);
        int wordcount =0;
        wordcount=getwordcount(sentence);
        char *pt = sentence;
        for(int i =0; i <wordcount; i++)
        {

         pt = breakIntoWords(pt,bsentence[i]);
        }



           for(int i =0; i< wordcount; i++)
        {
          for(int j=i; j<i;  j++)
           {
              int one = strlen(bsentence[i]);
              int two = strlen(bsentence[i+1]);

            if(one > two)
               {
                   char temp[120];
                   strcpy(temp,bsentence[i]);
                   strcpy(bsentence[i+1],temp);


           }

            }

        }
    char sen2[12];
     for(int i=0; i<wordcount; i++)
      {

          strcat(sen2,bsentence[i++]);
          strcat(sen2, " ");
       }
       strcpy(sentence,sen2);




        cout<<sentence;

    }
    char* breakIntoWords(char*p, char*pt)
    {
       int i =  0, j = 0;
      while( *p != ' ')
      {
       pt[i] = *p++;
       i++;

      }
      p++;
      pt[i]='\0';

      return p;
    }

Without using String class.

I have solved it finally. Any inputs on improving it is welcome.

    #include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAX_WORD_SIZE 30
#define MAX_LINE_SIZE 100
using namespace std;

int getWordCount(char* s)
{
   int wc = 0;
   while(*s == ' ')
     s++;
   while(*s != '\n')
   {
      while(*s != ' ' && *s != '\n')
      {
         s++;
       }

       if(*s == ' ')
       {
         while(*s == ' ')
            s++;
       }
       wc++;
   }
   return wc;
}
char* getWord(char* Source, char* word)
{
     while(*Source == ' ')
         Source++;
      int i =0;
      while(*Source != ' ' && *Source != '\n')
      {
         word[i] = *Source;
         Source++;i++;
       }
       word[i]='\0';
       if(*Source == ' ')
       {
         while(*Source == ' ')
            Source++;
       }
       return Source;


}
void sortSentence(char* p[], int wc)
{
   char *temp = new char[MAX_WORD_SIZE];
   for(int i =0; i<wc; i++)
   {
      for(int j = i; j< (wc-1); j++)
       {
           if(strlen(p[j]) > strlen(p[j+1]))
            {
                strcpy(temp,p[j]);
                strcpy(p[j],p[j+1]);
                strcpy(p[j+1],temp); 
             }
        }
    }
    delete[] temp;
}
int main()
{

 char* string;
 string = new char[MAX_LINE_SIZE];
 cout<<"Enter Sentence"<<endl;
 fgets(string,MAX_LINE_SIZE,stdin);
 int wordCount = getWordCount(string);
 char* pArrayOfPointers[30];
 char* tempString = string;
 for(int i =0; i< wordCount; i++)
 {
    char *ptemp;
      ptemp =new char[MAX_WORD_SIZE];
    pArrayOfPointers[i]= ptemp;
    tempString = getWord(tempString,pArrayOfPointers[i]);
    cout<<pArrayOfPointers[i]<<endl;          
  }
  sortSentence(pArrayOfPointers, wordCount);

  strcpy(string,pArrayOfPointers[0]);
  strcat(string," ");
  for(int i =1; i< wordCount; i++)
  {
     strcat(string,pArrayOfPointers[i]);
     strcat(string," ");

   }
   cout<<string;
 delete[] string;


}


Your code is vastly more complex than necessary because you’re not decomposing the problem into smaller tasks that would be easier to tackle.

Basically there are three steps:

  1. Decompose sentence into an array of words.
  2. Sort array of words by length.
  3. Output words, separated by spaces.

Each of these tasks is trivial in C++ and doesn’t require pointers or anything like that (which is a good thing. Pointers have their place in C but only rarely in C++).

For example, the first step can be solved using C++ IO streams and the vector container:

std::vector<std::string> words;

std::string word;
while (cin >> word)
    words.push_back(word);

This reads individual words from the standard input and stores them in a vector.

The second step can should be solved using the C++ standard library sort function.

The third step is a mere matter of iterating over the vector and pushing the words to the cout stream.

All in all, this shouldn’t take more than 15 lines of code.

If you don’t want to use a string class, your first step should be to write one. It doesn’t have to be fancy, but it should at least take care of the rudimentary mechanisms of handing the string’s memory, reading from input and writing to output.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜