字符串截取:
有这么一串字符串,“我abc爱ce你ef”要求你写一段程序,当输入4的时候得到的子串是“我ab”
当输入6的时候得到的子串为“我abc爱”不能出现“爱”字为半边。
/**
* 截取字符串,最后如果是半个中文,补上剩下的半个
* <功能详细描述>
* @param str 原始的字符串
* @param size 需要截取的长度
* @return 截取后的字符串
* @see [类、类#方法、类#成员]
*/
public static String subStringMore(String str, int size)
{
byte[] bb = null;
StringBuilder sb = new StringBuilder();
String temp = "";
int count = 0;
for (int j = 0; j < str.length(); j++)
{
temp = str.substring(j, j + 1);
sb.append(temp);
count += temp.getBytes().length;
if (count >= size)
{
break;
}
}
return sb.toString();
}
/**
* 截取字符串,最后如果是半个中文,舍掉最后的半个
* <功能详细描述>
* @param str 原始的字符串
* @param size 需要截取的长度
* @return 截取后的字符串
* @see [类、类#方法、类#成员]
*/
public static String subStringLess(String str, int size)
{
byte[] bb = null;
StringBuilder sb = new StringBuilder();
String temp = "";
int count = 0;
int nextLength = 0;
for (int j = 0; j < str.length(); j++)
{
temp = str.substring(j, j + 1);
sb.append(temp);
count += temp.getBytes().length;
if (count >= size)
{
break;
}
}
if (count > size)
{
return sb.substring(0, sb.length() - 1);
}
else
{
return sb.toString();
}
}