【问题标题】:Regarding String manipulation关于字符串操作
【发布时间】:2010-03-15 19:05:54
【问题描述】:

我有一个字符串 str,它可以包含如下值列表。我希望字符串中的第一个字母为大写,如果字符串中出现下划线,那么我需要将其删除并需要将其后面的字母设为大写。其余所有字母我希望它是小写的。

""
"abc" 
"abc_def"
"Abc_def_Ghi12_abd"
"abc__de"
"_"
Output:
""
"Abc"
"AbcDef"
"AbcDefGhi12Abd"
"AbcDe"
""

【问题讨论】:

  • 哇,这是一个好主意......希望你能成功而不用问那些初学者的问题,比如“String 类的文档在哪里说我想要的关于我需要的方法的所有内容做我的功课”。
  • 所以您有 一个 字符串,但显然该字符串中有 四个 个单独的“第一个”字母?
  • 这类似于 Commons Lang WordUtils.capitalize 所做的。
  • 显示你到目前为止尝试过的内容。
  • 其实和那个用户的另一个问题也很相似:stackoverflow.com/questions/2375649/…

标签: java string


【解决方案1】:

好吧,如果没有向我们展示您在这个问题上付出了任何的努力,这将有点模糊。

我在这里看到了两种可能性:

  1. 在下划线处拆分字符串,将this question 的答案应用于每个部分并重新组合它们。
  2. 创建一个StringBuilder,遍历字符串并跟踪你是否是

    • 在字符串的开头
    • 在下划线或之后
    • 别处

    并在将当前字符附加到StringBuilder 实例之前对其进行适当的操作。

【讨论】:

    【解决方案2】:
    1. 用空格替换_ (str.replace("_", " "))
    2. 使用WordUtils.capitalizeFully(str);(来自commons-lang
    3. 用空替换空间 (str.replace(" ", ""))

    【讨论】:

      【解决方案3】:

      您可以使用以下基于正则表达式的代码:

      public static String camelize(String input) {
        char[] c = input.toCharArray();
        Pattern pattern = Pattern.compile(".*_([a-z]).*");
        Matcher m = pattern.matcher(input);
        while ( m.find() ) {
          int index = m.start(1);
          c[index] = String.valueOf(c[index]).toUpperCase().charAt(0); 
        }
        return String.valueOf(c).replace("_", "");
      }
      

      【讨论】:

        【解决方案4】:

        在 java.util.regex 包中使用 Pattern/Matcher:

        对于数组中的每个字符串,请执行以下操作:

        StringBuffer output = new StringBuffer();
        Matcher match = Pattern.compile("[^|_](\w)").matcher(inStr);
        while(match.find()) {
           match.appendReplacement(output, matcher.match(0).ToUpper());
        }
        match.appendTail(output);
        
        // Will have the properly capitalized string.
        String capitalized = output.ToString();
        

        正则表达式查找字符串的开头或下划线“[^|_]” 然后将下面的字符放入一个组“(\w)”

        然后代码遍历输入字符串中的每个匹配项,大写第一个满足组。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-12-19
          • 2012-09-27
          • 2021-07-17
          • 2019-03-25
          • 1970-01-01
          • 1970-01-01
          • 2016-06-29
          相关资源
          最近更新 更多