Skip to content

Instantly share code, notes, and snippets.

@nathanchen
Created August 14, 2012 05:33
Show Gist options
  • Select an option

  • Save nathanchen/3346617 to your computer and use it in GitHub Desktop.

Select an option

Save nathanchen/3346617 to your computer and use it in GitHub Desktop.
JAVA - String 前后pad以及repeat
/**
* <li>{@code padStart("7", 3, '0')} returns {@code "007"}
* <li>{@code padStart("2010", 3, '0')} returns {@code "2010"}
*/
public static String padStart(String string, int minLength, char padChar)
{
checkNotNull(string);
if(string.length() >= minLength)
{
return string;
}
StringBuffer sBuf = new StringBuffer(minLength);
for(int i = string.length(); i < minLength; i++)
{
sBuf.append(padChar);
}
sBuf.append(string);
return sBuf.toString();
}
/**
* <li>{@code padEnd("4.", 5, '0')} returns {@code "4.000"}
* <li>{@code padEnd("2010", 3, '!')} returns {@code "2010"}
*/
public static String padEnd(String string, int minLength, char padChar)
{
checkNotNull(string);
if(string.length() >= minLength)
{
return string;
}
StringBuffer sBuf = new StringBuffer(minLength);
sBuf.append(string);
for(int i = string.length(); i < minLength; i++)
{
sBuf.append(padChar);
}
return sBuf.toString();
}
/**
* {@code repeat("hey", 3)} returns the string
* {@code "heyheyhey"}
*/
public static String repeat(String string, int count)
{
checkNotNull(string);
checkArgument(count >= 0, "invalid count: %s", count);
StringBuffer sBuf = new StringBuffer(string.length() * count);
for(int i = 0; i < count; i++)
{
sBuf.append(string);
}
return sBuf.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment