Given a line, adjust this line to the page width.

For example, given “Dog is cute” (length of chars is 11) and the page width is 15, adjust the line to “Dog is cute”. The extra spaces should be distributed as much even as possible. Assume there is no space before the first word or after the last word.

C++:
01 int wordCount(char* s)
02 {
03      int cnt=0;
04      int i=0;
05      bool flag=false;
06      while(true){
07          if(((s[i]>=‘a’)&&(s[i]<=‘z’))||((s[i]>=‘A’)&&(s[i]<=‘Z’))){
08              if(flag==false)
09                  flag=true;
10          }else if(flag==true){
11              cnt++;
12              flag=false;
13          }
14          i++;
15          if(s[i]==){
16              if(flag==true)
17                  cnt++;
18              break;
19          }
20      }
21      return cnt;
22 }
23 
24 int charCount(char* s)
25 {
26     int i=0;
27     int cnt=0;
28     while(s[i]!=){
29         if(((s[i]>=‘a’)&&(s[i]<=‘z’))||((s[i]>=‘A’)&&(s[i]<=‘Z’)))
30             cnt++;
31         i++;
32     }
33     return cnt;
34 }
35 
36 char* adjustLine(char* s, int k)
37 {
38     int n=wordCount(s);
39     int m=charCount(s);
40     int len=(km)/(n1);
41     int r=(km)%(n1);
42     int j=0;
43     char* t=new char[k+1];
44 
45     for(int i=0;j<k;i++){
46         if(((s[i]>=‘a’)&&(s[i]<=‘z’))||((s[i]>=‘A’)&&(s[i]<=‘Z’))){
47             t[j++]=s[i];
48             continue;
49         }
50         for(int p=0;p<len;p++)
51             t[j++]=‘ ‘;
52         if(r>0){
53             t[j++]=‘ ‘;
54             r;
55         }
56     }
57     t[j]=;
58     return t;
59 }
Advertisements
This entry was posted in String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s