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

考虑到我有这样的 String "Abcd123",我需要首先检测我的字符串是否包含数字(0-9),然后在第一个数字之前插入一个空格,所以我的最终 String 是"Abcd 123"


达令说
浏览 133回答 2
2回答

素胚勾勒不出你

您可以使用 :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

繁星coding

你可以使用这个简单的逻辑:&nbsp; &nbsp; String str = "Abcd123";&nbsp; &nbsp; String newStr = "";&nbsp; &nbsp; for (int i = 0; i < str.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (Character.isDigit(str.charAt(i))){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newStr = newStr + " " + str.substring(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newStr = newStr + str.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(newStr);在这里,我们遍历字符串中的每个字符,并在找到第一个数字后立即中断循环。输出 :第 123 章
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java