美文网首页
截取emoji表情符

截取emoji表情符

作者: 周末不加班 | 来源:发表于2019-07-12 22:57 被阅读0次

    工作中遇到一个问题:为保护用户隐私 在评论区将用户名中间的字段使用*号代替
    有的奇葩用户名中夹杂有表情字符,此时使用substring()进行截取操作,结果就有可能是乱码或者不符合要求因为JVM运行时使用UTF-16编码,实际Java自带特殊字符截取的方法offsetByCodePoints

    例如String 类型的字符串是一组表情, 现在要将他进行一下操作:

    String emoji="🐷👀🎈😍📌";
    

    获取表情个数

    • codePointCount方法返回整个String中的表情个数,此时codePointCount=5
    int codePointCount = emoji.codePointCount(0, emoji.length()); //返回指定文本中的Unicode代码点数
    

    截取最后一个表情

    sta=4 ,end=5
    从第4个开始(不包括) 截取到第5个(包括)
    确定截取的位置后,再使用substring截取

    int sta =emoji.offsetByCodePoints(0 , codePointCount-1);//获取倒数第2个表情结束的位置(实际也是倒数第一个表情开始的位置)
    int end =emoji.offsetByCodePoints(0 , codePointCount); //获取最后一个表情结束的位置
    
    String subEmoji = emoji.substring(sta, end);    //subEmoji=📌
    

    如果截取第一个,开始的位置为offsetByCodePoints(0 , 0); 结束为offsetByCodePoints(0 ,1);

    中间三个用***代替

    int repSta =emoji.offsetByCodePoints(0 , 1);//不包括第一个表情
    int repEnd =emoji.offsetByCodePoints(0 , 4); //范围取第234个
    
    StringBuffer buffer = new StringBuffer(emoji);
    buffer.replace(repSta , repEnd , "***");
    System.out.println(" buffer="+buffer.toString());   //buffer=🐷****📌
    

    相关文章

      网友评论

          本文标题:截取emoji表情符

          本文链接:https://www.haomeiwen.com/subject/rjpykctx.html