Last active
August 29, 2015 14:07
-
-
Save 0532/ee26672e398198752786 to your computer and use it in GitHub Desktop.
字符串的拼接
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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