在大写字符java之间添加空格

我是 Java 的初学者。下面是我写的一段代码。目的是在每个大写字符之间添加一个空格,例如 string="ILoveMyDog" 到 "I Love My Dog"。然而,这段代码的结果是“ILoveMy Dog”。有人可以帮我弄清楚出了什么问题吗?upperCaseList 是另一种提取所有大写字符的索引并将它们放入列表的方法,我很确定那部分是正确的


for (int i = 0; i < upperCaseList.size(); i++) {

    newStr = w.replace(w.substring(upperCaseList.get(i), upperCaseList.get(i)+1), " "+ w.substring(upperCaseList.get(i), upperCaseList.get(i)+1));

    }

return newStr


慕尼黑8549860
浏览 214回答 2
2回答

当年话下

这是因为您String.replace通过newStr在循环内重新分配来覆盖结果。因此,您只能看到最后一次替换的效果。假设 的内容upperCaseList是1, 5, 7。在循环迭代 1 之后,newStr有I LoveMyDog在循环迭代 2 之后,newStr有ILove MyDog(您没有使用先前的结果,而是使用原始字符串)在循环迭代 3 之后,newStr有ILoveMy Dog试试这个,String newStr = w;for (int i = 0; i < upperCaseList.size(); i++) {&nbsp; &nbsp; newStr = newStr.replace(w.substring(upperCaseList.get(i), upperCaseList.get(i)+1), " "+ w.substring(upperCaseList.get(i), upperCaseList.get(i)+1));}不过有很多方法可以解决这个问题。不是存储包含大写字符的索引列表并使用String.substringand String.replace,您可以使用StringBuilder通过循环字符并检查它是否是大写/小写来从原始字符串构建字符串。StringBuilder resultBuilder = new StringBuilder();for (int i = 1; i < w.length(); i++) { //Note: Starting at index 1&nbsp; &nbsp; if (Character.isUpperCase(w.charAt(i))) {&nbsp; &nbsp; &nbsp; &nbsp; resultBuilder.append(" ")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .append(w.charAt(i));&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; resultBuilder.append(w.charAt(i));&nbsp; &nbsp; }}System.out.println(resultBuilder.toString());

哈士奇WWW

不确定您是如何创建 upperCaseList 的,我建议为所有人创建一个循环。希望下面的代码可以满足您的要求。public void test(){&nbsp; &nbsp; String str ="ILoveMyDog";&nbsp; &nbsp; StringBuilder strBuilder&nbsp; = new StringBuilder();&nbsp; &nbsp; for (int i = 0; i< str.length() ; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if(Character.isUpperCase(str.charAt(i))){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //add space&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; strBuilder.append(" ");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; //add the orginal char&nbsp; &nbsp; &nbsp; &nbsp; strBuilder.append(str.charAt(i));&nbsp; &nbsp; }&nbsp; &nbsp; //use toString method&nbsp;&nbsp; &nbsp; System.out.println(strBuilder.toString());}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java