加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 用多个句子将字符串中的第一个单词大写

发布时间:2020-12-14 23:49:45 所属栏目:Java 来源:网络整理
导读:例如: String s =“这是a.line是.over” 应该出来 “这是a.Line is.Over” 我想过两次使用字符串标记器 -first split using"." -second split using " " to get the first word -then change charAt[0].toUpper 现在我不确定如何使用字符串标记符的输出作为
例如:

String s =“这是a.line是.over”

应该出来

“这是a.Line is.Over”

我想过两次使用字符串标记器

-first split using"."

 -second split using " " to get the first word

 -then change charAt[0].toUpper

现在我不确定如何使用字符串标记符的输出作为另一个的输入?

我也可以使用split方法生成我尝试过的数组

String a="this is.a good boy";
     String [] dot=a.split(".");

       while(i<dot.length)
     {
         String [] sp=dot[i].split(" ");
            sp[0].charAt(0).toUpperCase();// what to do with this part?

解决方法

使用StringBuilder,无需拆分和创建其他字符串,依此类推,请参阅代码
public static void main(String... args) {

String text = "this is a.line is. over";

int pos = 0;
boolean capitalize = true;
StringBuilder sb = new StringBuilder(text);
while (pos < sb.length()) {
    if (sb.charAt(pos) == '.') {
        capitalize = true;
    } else if (capitalize && !Character.isWhitespace(sb.charAt(pos))) {
        sb.setCharAt(pos,Character.toUpperCase(sb.charAt(pos)));
        capitalize = false;
    }
    pos++;
}
System.out.println(sb.toString());
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读