为了账号安全,请及时绑定邮箱和手机立即绑定

检测字符串包含一个数字然后在它之前插入一个空格

检测字符串包含一个数字然后在它之前插入一个空格

达令说 2021-12-22 19:11:49
考虑到我有这样的 String "Abcd123",我需要首先检测我的字符串是否包含数字(0-9),然后在第一个数字之前插入一个空格,所以我的最终 String 是"Abcd 123"
查看完整描述

2 回答

?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

您可以使用 :


String str = "Abcd123";

if (str.replaceAll("\\D", "").length() > 0) {  // check if the string contain numbers

    str = str.replaceFirst("\\d", " $0");      // if yes put a space before the first degit

}

输出


Abcd 123


查看完整回答
反对 回复 2021-12-22
?
繁星coding

TA贡献1797条经验 获得超4个赞

你可以使用这个简单的逻辑:


    String str = "Abcd123";

    String newStr = "";


    for (int i = 0; i < str.length(); i++) {

        if (Character.isDigit(str.charAt(i))){

            newStr = newStr + " " + str.substring(i);

            break;

        } else {

            newStr = newStr + str.charAt(i);

        }

    }

    System.out.println(newStr);

在这里,我们遍历字符串中的每个字符,并在找到第一个数字后立即中断循环。


输出 :


第 123 章


查看完整回答
反对 回复 2021-12-22
  • 2 回答
  • 0 关注
  • 132 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号