Skip to content

Instantly share code, notes, and snippets.

@x3chaos
Created March 26, 2014 00:04
Show Gist options
  • Save x3chaos/9774184 to your computer and use it in GitHub Desktop.
Save x3chaos/9774184 to your computer and use it in GitHub Desktop.
Centering text in a console window
package org.x3chaos.lel;
/**
* Some utilities for formatting Strings in console windows
*/
public class StringUtils {
/**
* Generates a String that contains the given line, centered with spaces
* inside the given width; used to create centered headers or the like. If
* the given width is shorter than the line itself, no changes will be made.
*
* @param line
* The line to center
* @param width
* The width in which to center the line (i.e. the width of the
* terminal window)
* @return A String
*/
public static String center(String line, int width) {
// if the width is longer than the line, no changes
if (width < line.length()) return line;
int totalSpaces = width - line.length();
int pre = totalSpaces / 2;
int post = totalSpaces - pre;
/*
* the above line may look weird, but so is integer division. basically,
* an integer divided by an integer, stored in an integer variable, will
* always truncate any remaining decimal, thus essentially rounding it
* down. so if totalSpaces is odd (i.e. 15), the generated line won't
* fill the width (15 / 2 = 7, in integer division, and 7 + 7 = 14, and
* obviously 14 != 15). so yeah.
*/
return createSpaces(pre) + line + createSpaces(post);
}
/**
* Generates a String containing the given number of spaces. Returns an
* empty string for arguments that are less than or equal to zero.
*
* @param count
* The number of spaces
* @return a String that contains the given number of spaces
*/
public static String createSpaces(int count) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < count; i++) {
// if count <= 0, this loop will never even run, so it's fine to
// exclude that check
result.append(" ");
}
return result.toString();
}
}
package org.x3chaos.lel;
/**
* A testing class for StringUtils.java
*/
public class TestingClass {
private static final int WIDTH = 80; // standard Windows console width
public static void main(String[] args) {
String s1 = "Header"; // 6 characters
String s2 = "======="; // 7 characters
print(StringUtils.center(s1, WIDTH));
print(StringUtils.center(s2, WIDTH));
}
public static void print(String line) {
System.out.printf("|%s|\n", line);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment