【问题标题】:How to get UpperCamelCase using StringUtils?如何使用 StringUtils 获取 UpperCamelCase?
【发布时间】:2019-08-02 21:08:57
【问题描述】:

我似乎无法让 StringUtils.capitalize 真正将我的整个单词字符串大写。

我尝试了各种方法,但我最终得到了句子类型的案例。我尝试在要打印的内容中使用 StringUtils.capitalize,但这也不起作用。我查找的内容也没有任何帮助。

  File file = 
      new File("C:\\Users\\mikek\\Desktop\\name.txt"); 
    BufferedReader abc = new BufferedReader(new FileReader(file));
List<String> data = new ArrayList<String>();
String s;
String t;
while((s=abc.readLine()!=null) {
    data.add(s);

    System.out.println("public static final Block " + s.toUpperCase() + "     = new "
+  StringUtils.capitalize(s).replace("_","") + "(\"" + s + "\", Material.ROCK);");
}

abc.close();
 }

预期:木炭块 得到:木炭块

【问题讨论】:

  • 我不明白。除了Charcoal Block 之外,你是要存储在data 还是什么?
  • 文档说“大写一个字符串,根据 Character.toTitleCase(int) 将第一个字符更改为标题大小写。没有其他字符被更改。”,所以它不会打扰你的其他单词细绳。它只使用第一个字符,没有别的。该文档还建议查看WordUtils.capitalize(String)。你应该听取他们的建议。
  • @Luiggi 我正在尝试制作一个模组工具。添加每个项目非常繁琐,我正在写这篇文章以提高我的效率。实际上,我正在生成代码以复制/粘贴到我的 mod 中。
  • 在调用data.add(t) 后更改t 不会更改data 中的内容。它只是让变量t 指向一个不同的字符串对象,这个对象从未添加到任何列表中。
  • VGR 所以基本上,当我从我的文本文件中引入“charcoal_block”时,“charcoal_block”变成了字符串并用“”替换了“_”编辑了那个字符串?就像,它变成“木炭块”,因为 .capitalize 只将每个单独的字符串大写,而我没有做任何事情使它成为 2 个字符串? (如果这有任何意义)

标签: java string-utils


【解决方案1】:

这个怎么样??

        String s = "camel case word";
        String camelCaseSentence = "";
        String[] words = s.split(" ");
        for(String w:words){
            camelCaseSentence += w.substring(0,1).toUpperCase() + w.substring(1) + " ";

        }
        camelCaseSentence = camelCaseSentence.substring(0, camelCaseSentence.length()-1);
        System.out.println(camelCaseSentence);

【讨论】:

  • 这在我将 s.split(" ") 替换为 s.split("_") 时有效。然后我添加了 camelCaseSentence.replace(" ","") 而不是 t。谢谢!
【解决方案2】:

Chris Katric 帮我弄清楚了什么:

File file = 
  new File("C:\\Users\\mikek\\Desktop\\name.txt"); 
BufferedReader abc = new BufferedReader(new FileReader(file));
List<String> data = new ArrayList<String>();
String s;

while((s=abc.readLine())!=null) {
data.add(s);
String camelCaseSentence = "";
    String[] words = s.split("_");
    for(String w:words){
        camelCaseSentence += w.substring(0,1).toUpperCase() + w.substring(1) + " ";

    }
    camelCaseSentence = camelCaseSentence.substring(0, camelCaseSentence.length()-1);

System.out.println("public static final Block " + s.toUpperCase() + " = new "
+  camelCaseSentence.replace(" ", "") + "(\"" + s + "\", Material.ROCK);");
}

abc.close();
 }

现在我得到(对于 System.out.println 的全部部分): "public static final Block CHARCOAL_BLOCK = new CharcoalBlock("charcoal_block", Material.ROCK);"就像我想要的那样。

【讨论】:

    猜你喜欢
    • 2015-08-30
    • 2014-03-10
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多