日期:2014-05-20  浏览次数:20792 次

java中有类似sql中rpad这个方法的吗?
如题,JAVA中有类似这种字符串右补齐的方法吗?

PS:
rpad(var_name,5, 'a ');
当var_name   =   'bb '的时候,返回值为 'bbaaa ';
当var_name   =   'bbb '的时候,返回值为 'bbbaa ';

请朋友们指点下,谢谢。

------解决方案--------------------
自己写吧!
public String rpad(String str,int num,String pad){
String n_str=str;
if(str==null)
n_str= " ";
for(int i=str.length();i <num;i++){
n_str+=pad;
}
return n_str;
}
------解决方案--------------------
StringBuffer的insert方法和这个差不多吧
------解决方案--------------------
没有:
用这个吧
package com.capitalnd.util;

import java.text.*;

/**
* StringPadderはひもに左のパッドおよび右のパッドの機能性を提供する
* @author penglee
* <br> 2007-07-03
*/
public class StringPadder {
private static StringBuffer strb;
private static StringCharacterIterator sci;

/** method to left pad a string with a given string to a given size. This
* method will repeat the padder string as many times as is necessary until
* the exact specified size is reached. If the specified size is less than the size of
* the original string then the original string is returned unchanged.
* Example1 - original string "cat ", padder string "white ", size 8 gives "whitecat ".
* Example2 - original string "cat ", padder string "white ", size 15 gives "whitewhitewhcat ".
* Example3 - original string "cat ", padder string "white ", size 2 gives "cat ".
* @return String the newly padded string
* @param stringToPad The original string
* @param padder The string to pad onto the original string
* @param size The required size of the new string
*/
public static String leftPad (String stringToPad, String padder, int size)
{
if (padder.length() == 0)
{
return stringToPad;
}
strb = new StringBuffer(size);
sci = new StringCharacterIterator(padder);

while (strb.length() < (size - stringToPad.length()))
{
for (char ch = sci.first(); ch != CharacterIterator.DONE ; ch = sci.next())
{
if (strb.length() < size - stringToPad.length())
{
strb.insert( strb.length(),String.valueOf(ch));
}
}
}
return strb.append(stringToPad).toString();
}

/** method to right pad a string with a given string to a given size. This
* method will repeat the padder string as many times as is necessary until
* the exact specified size is reached. If the specified size is less than the size of
* the original string then the original string is returned unchanged.
* Example1 - original string "cat ", padder string "white ", size 8 gives "catwhite ".
* Example2 - original string "cat ", padder string "white ", size 15 gives "catwhitewhitewh ".
* Example3 - original string "cat ", padder string "white ", size 2 gives "cat ".
* @return String the newly padded string
* @param stringToPad The original string
* @param padder The string to pad onto the original string
* @param size The required size of the new string
*/
public static String rightPad (String stringToPad, String padder, int size)