日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

安字节截取字符串

發(fā)布時間:2025/3/17 编程问答 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 安字节截取字符串 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
package cn.ilex.demo;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SplitString {


??public static void main(String[] args) throws IOException {

????String s = "我ABC漢DEF";
????????????????
????System.out.println(getStr(s,4));

??}
??
??public static String getStr(String str,int bytes){
????String _str="";
????int count=0;
????Pattern p= Pattern.compile("[\\u4e00-\\u9fa5]");
????char[] c=str.toCharArray();
????for (int i=0;i<c.length;i++){
??????String s=new String(c,i,1);
??????Matcher m=p.matcher(s);
??????if (m.find()){
????????count+=2;
??????}else
????????count+=1;
??????if (count<=bytes){
????????_str=_str+s;
??????}else
????????break;
????}
????return _str;
??}
??
??
????????/**
???????? * 截取字符串,并在截取的字符串后添加指定后綴,如果字符串長度小于指定長度時不添加后綴
???????? * 原樣返回。
???????? *
???????? * @param str????????????需要截取的字符串
???????? * @param length???? 截取字符串的長度,字母算 1 個字,全角字符算 2 個字
???????? * @param suffix???? 超出時添加的后綴
???????? * @return
???????? */

????????public static String truncate(String str, int length, String suffix) {
????????????????if((str == null) || (str.length() == 0) || (length < 1)) {
????????????????????????return str;
????????????????}
????????????????char[] chs = str.toCharArray();
????????????????int len = 0;
????????????????int offset = 0;
????????????????for(int i = 0; i < chs.length; i++, offset++) {
????????????????????????len += (chs[i] > 0xff) ? 2 : 1;
????????????????????????if(len > length) {
????????????????????????????????break;
????????????????????????}
????????????????}
????????????????if(offset == chs.length) {
????????????????????????return str;
????????????????}
????????????????if(suffix == null || suffix.trim().length() == 0) {
????????????????????????return new String(chs, 0, offset);
????????????????}
????????????????return new String(chs, 0, offset) + suffix.trim();
????????}
}

轉載于:https://blog.51cto.com/ilexes/367544

總結

以上是生活随笔為你收集整理的安字节截取字符串的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。