【问题标题】:Checking if the word is uppercase, and changing only the first letter检查单词是否为大写,只更改第一个字母
【发布时间】:2012-04-23 04:02:47
【问题描述】:

我在这个论坛上搜索了一下,似乎只能找到关于如何使每个单词的首字母大写的问题。这不是我想要的。

我正在寻找可以检查字符串中所有单词的东西,如果它们是大写的,则将字母更改为小写,第一个除外。

比如,假设字符串是:

“HI 堆栈溢出”

它会变成:

“你好 Stackoverflow”

或者:

“我在 stackoverflow dot com 上提问”

它会变成:

“我在 stackoverflow dot com 上提问”

【问题讨论】:

标签: java string uppercase


【解决方案1】:

我会使用 StringTokenizer 类将字符串分解为单独的单词。然后您可以将每个令牌作为单独的字符串并进行比较:

String line = "A BIG Thing that Something"

StringTokenizer st = new StringTokenizer(line);

        while(st.hasMoreTokens)
            {
                String a = st.nextToken();
                if(a.equals(a.toUpperCase())){
                    System.out.println(a.charAt(0) + a.substring(1).toLowerCase());
                }else{
                    System.out.println(a);
                    }
            }

类似的东西...你需要记住导入 StringTokenizer,它是 java.util 包的一部分。

【讨论】:

  • if(a.equals(a.toUpperCase()) 是做什么的?只需将令牌更改为大写?在那种情况下,你为什么需要if()
  • 该部分检查 a 是否等于大写自身(即 a 是否为大写)。 if 是因为发布者想让这些类型的代币只有一个领先的资本,而 else if 是为了保持其他一切不变。这有意义吗?
  • 谢谢大家,你知道我怎么能做到,如果第一个字母是一个符号(即“:”)它不会小写第二个字符。所以人们可以做 :D 而不是去 :d?
  • @CodyThompson:您必须使用a.charAt(0) 添加更多条件。检查 ASCII 表以查看要比较的内容。我没有给你答案,因为learning by searching >>>> asking ;-)
【解决方案2】:
   public static void main(String[] args) {
      String org= "HI STACKOVERFLOW";
      String [] temp=org.split(" ");
      int len=temp.length;
      String ne = ".";
      for(int i=0;i<len;i++)
      {

         temp[i]=temp[i].toUpperCase();
         temp[i]=(temp[i].substring(0, 1)).toUpperCase()+(temp[i].substring(1, temp[i].length())).toLowerCase();
        System.out.print(temp[i]+" "); 
      }

    }

输出 Hi Stackoverflow

【讨论】:

    【解决方案3】:

    如果您愿意在您的项目中合并一个库,我很确定 Apache Commons-lang StringUtils 具有您需要的功能类型。

    【讨论】:

      猜你喜欢
      • 2021-12-07
      • 2018-07-09
      • 2021-08-19
      • 1970-01-01
      • 2012-11-02
      • 2021-06-28
      • 2021-09-13
      • 1970-01-01
      相关资源
      最近更新 更多