Switch to full style
C++ code examples
Post a reply

String Formatter

Thu Nov 13, 2008 3:23 pm

Format string using C++
cpp code
/*
* Formats the input text into 75 character wide lines. Takes each
* non-blank unit as a word, and fits as many as possible on each
* line. It separates words by one space, unless the word ends in
* a period, !, or ?, and the next word starts with a capitol,
* in which case it gets two spaces.
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define WIDTH 75 /* Width of a line. */
#define WORDSIZE 50 /* Storage size of input word. */

main()
{
char line[WIDTH+1]; /* Output line. */
char word[WORDSIZE]; /* Input word. */
int linesize; /* Accumulated line size. */
int wordsize; /* Size of inbound word. */
int numspace; /* Number of separating spaces. */

/* Initialize the output line. */
line[0] = 0;
linesize = 0;

/* Read all the words in the input file. */
while(scanf("%s", word) == 1)
{
/* How long is it? */
wordsize = strlen(word);

/* Decide how many spaces need to after the word. */
if(linesize == 0)
numspace = 0;
else if ((line[linesize-1] == '.' ||
line[linesize-1] == '?' ||
line[linesize-1] == '!') &&
isupper(word[0]))
numspace = 2;
else
numspace = 1;

/* See if it fits on the line, complete with separating
space. */
if(linesize + wordsize + numspace > WIDTH)
{
/* Too long. Spit out the line, and reset. */
printf("%s\n", line);
strcpy(line, word);
linesize = wordsize;
}
else
{
/* Fits. Add it to the line. */
strcat(line, " " + (2 - numspace));
strcat(line, word);
linesize += wordsize + numspace;
}
}

/* Print the last line. */
printf("%s\n", line);
}


This is a Simple String Formatter



Post a reply
  Related Posts  to : String Formatter
 recursive string reversal- reverse string     -  
 check if string ends with specific sub-string in php     -  
 Splitting a String Based on a Found String     -  
 check if string start with a specific sub-string in PHP     -  
 String token for string split     -  
 Pad a string to a certain length with another string     -  
 String to sql.Date     -  
 what is string toString()     -  
 get number from string     -  
 String Flatten (C++)     -  

Topic Tags

C++ Strings