搜尋此網誌

2013年8月24日 星期六

【Java】將javascript的substr函式以java來表示

由於java並沒有類似javascript中的substr功能(或者說找不到...),所以以java code呈現javascript的substr。

/**<p>Example: Different between with String.substring and getSubstr<br>
* String a ="654321"; <br>
* b=a.substring(1,2); //b="5"<br>
* b=getSubstr(a,1,2); //b="54" <br>
*
* @param s (the word)
* @param beginningIndex (the beginning index of word)
* @param length (the length of word)
* @return subStr 

*/
String getSubstr(String s, int beginningIndex, int length) {
char[] temp = s.toCharArray();
length = temp.length < length ? temp.length : length;

StringBuilder subStr = new StringBuilder();
for (int i = beginningIndex; i < length; i++) {
subStr.append(temp[i]);
}

return subStr.toString();
}

String getSubstr(String s, int beginningIndex) {
char[] temp = s.toCharArray();

StringBuilder subStr = new StringBuilder();
for (int i = beginningIndex; i < s.length(); i++) {
subStr.append(temp[i]);
}

return subStr.toString();

//簡化
  return getSubstr(s,beginningIndex,s.length());

}

沒有留言: