Skip to content

Instantly share code, notes, and snippets.

@0532
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0532/ee26672e398198752786 to your computer and use it in GitHub Desktop.
Save 0532/ee26672e398198752786 to your computer and use it in GitHub Desktop.
字符串的拼接
package pub.tools;
import java.io.UnsupportedEncodingException;
public class StringPad {
public static String pad4ChineseToByteLength(boolean isLeftPad, String srcStr, int totalByteLength, String padStr) {
if (srcStr == null) {
return null;
}
int srcByteLength = srcStr.getBytes().length;
if (padStr == null || "".equals(padStr)) {
padStr = " ";
} else if (padStr.getBytes().length > 1 || totalByteLength <= 0) {
throw new RuntimeException("参数错误");
}
StringBuilder rtnStrBuilder = new StringBuilder();
if (totalByteLength >= srcByteLength) {
if (isLeftPad) { // 左补
for (int i = 0; i < totalByteLength - srcByteLength; i++) {
rtnStrBuilder.append(padStr);
}
rtnStrBuilder.append(srcStr);
} else { // 右补
rtnStrBuilder.append(srcStr);
for (int i = 0; i < totalByteLength - srcByteLength; i++) {
rtnStrBuilder.append(padStr);
}
}
} else {
byte[] rtnBytes = new byte[totalByteLength];
try {
System.arraycopy(srcStr.getBytes("GBK"), 0, rtnBytes, 0, totalByteLength);
rtnStrBuilder.append(new String(rtnBytes, "GBK"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return rtnStrBuilder.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment