Created
June 8, 2012 09:43
-
-
Save STAR-ZERO/2894745 to your computer and use it in GitHub Desktop.
全角・半角、左右trim
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
/** | |
* 文字列処理クラス | |
* | |
*/ | |
public class StringUtil { | |
/** 半角スペース */ | |
private static final char SPACE_CHAR_HALF = ' '; | |
/** 全角スペース */ | |
private static final char SPACE_CHAR_WID = ' '; | |
/** | |
* 両端の空白(全角・半角)を除去します。 | |
* | |
* @param value 対象文字列 | |
* @return trim後文字列 | |
*/ | |
public static String trim(String value) { | |
return ltrim(rtrim(value)); | |
} | |
/** | |
* 左側の空白(全角・半角)を除去します。 | |
* | |
* @param value 対象文字列 | |
* @return 編集後文字列 | |
*/ | |
public static String ltrim(String value) { | |
if (value == null || value.equals("")) { | |
return value; | |
} | |
int pos = 0; | |
for (int i = 0; i < value.length(); i++) { | |
char c = value.charAt(i); | |
if (c != SPACE_CHAR_HALF && c != SPACE_CHAR_WID) { | |
break; | |
} | |
pos = i + 1; | |
} | |
if (pos > 0) { | |
return value.substring(pos); | |
} else { | |
return value; | |
} | |
} | |
/** | |
* 右側の空白(全角・半角)を除去します。 | |
* | |
* @param value 対象文字列 | |
* @return 編集後文字列 | |
*/ | |
public static String rtrim(String value) { | |
if (value == null || value.equals("")) { | |
return value; | |
} | |
int pos = 0; | |
for (int i = value.length() - 1; i >= 0; i--) { | |
char c = value.charAt(i); | |
if (c != SPACE_CHAR_HALF && c != SPACE_CHAR_WID) { | |
break; | |
} | |
pos = i; | |
} | |
if (pos > 0) { | |
return value.substring(0, pos); | |
} else { | |
return value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment