Start New Discussion within our Software Development Community

This program outputs a given string word-wrapped to N columns in console. The program can also handle words whose length is greater than N.

#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#define MAXSIZE 150

void WordWrap( char *str, int N );

int main( )
{
	char *s1 = "This is an sample string word wrapped to 10 columns";
	char *s2 = "The following word wouldn't fit in 9 columns: EXTRATELECOMMUNICATIONS";
	char s3[MAXSIZE];
	int n;

	printf("0123456789\n");
	WordWrap( s1, 10 );
	printf("\n\n");
	WordWrap( s2, 9 );
	printf("\n\n");
	printf("Enter a string: ");
	fgets( s3, MAXSIZE, stdin );
	printf("Enter number of columns to wrap to: ");
	scanf("%d", &n );
	printf("\n\n");
	WordWrap( s3, n );
	getch();
	return 0;
}

		// Outputs a string wrapped to N columns
void WordWrap( char *str, int N )
{
	int i,j,k,pos;
	i = pos = 0;
	char word[MAXSIZE];

	while( 1 )
	{
		j = 0;
		while( !isspace( str[i]) )	// Find next word
		{
			if( str[i] == '\0' )
				break;
			word[j] = str[i];
			i++;
			j++;
		}

		word[j] = '\0';			// The value of j is the word length

		if( j > N )					// Word length is greater than column length
		{							// print char-by-char
			k = 0;
			while( word[k] != '\0' )
			{
				if( pos >= N-1 )
				{
					if( k != 0 )
						putchar('-');	// print '-' if last-but-one column
					pos = 0;
					putchar('\n');
				}
				putchar( word[k] );
				pos++;
				k++;
			}
		}
		else
		{
			if( pos + j > N )		// Word doesn't fit in line
			{
					putchar('\n');
				pos = 0;
			}

			printf("%s", word );
			pos += j;
		}
		if( pos < N-1 )		// print space if not last column
			{
				putchar(' ');
				pos++;
			}


		if( str[i] == '\0' )
			break;

		i++;		// Skip space
	}	// end of while(1)
}