Over a million developers have joined DZone.

Groovy - Plain Text Word Wrap Method

·
// Groovy Method to perform word-wrap to a specified length.
// Returns a List of strings representing the wrapped text


// Quick and Dirty method for plain text word-wrap to a specified width
static class TextUtils {
	
	static String[] wrapntab(input, linewidth = 70, indent = 0) throws IllegalArgumentException {
		if(input == null)
			throw new IllegalArgumentException("Input String must be non-null")
		if(linewidth <= 1)
			throw new IllegalArgumentException("Line Width must be greater than 1")
		if(indent <= 0)
			throw new IllegalArgumentException("Indent must be greater than 0")
		
		def olines = []
		def oline = " " * indent
		
		input.split(" ").each() { wrd ->
			if( (oline.size() + wrd.size()) <= linewidth ) {
				oline <<= wrd <<= " "
			}else{
				olines += oline
				oline = " " * indent
			}
		}
		olines += oline
		return olines
	}
}

// TEST
// the input String
input = "Note From SUPPLIER: Booking confirmed by fax.  4 standard rooms - 3 twin shared, 1 single room, please advise if guests require meals.. "

// call static wrapntab method to break the input string into 70 char wide lines with a 4 char initial indent
olines = TextUtils.wrapntab(input,70,4)

// print the output
olines.each() {
	println it
}

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}