简体   繁体   English

java中的简单字符串连接操作

[英]simple string concat manipulation in java

I want to get the following output: 我想获得以下输出:

Hello Steve Andrews! 史蒂夫安德鲁斯你好!

These are my variables: 这些是我的变量:

a = "steve";
b = "Andrew"

I tried this: 我试过这个:

System.out.print("Hello " + a + " " + b + "s");

I don't know where to put .toUpper() for steve . 我不知道在哪里放.toUpper() for steve The s should be in uppercase. s应该是大写的。 How do I do this? 我该怎么做呢?

Use StringUtils.capitalize(a) , 使用StringUtils.capitalize(a)

"Hello " + StringUtils.capitalize(a) + " " + b + "s"

Capitalizes a String changing the first letter to title case as per Character.toTitleCase(char). 根据Character.toTitleCase(char)将字符串首字母大写更改为标题大小写。 No other letters are changed. 没有其他字母被更改。

You could use StringUtils.capitalize(str) , or if you want to do it by yourself: 您可以使用StringUtils.capitalize(str) ,或者如果您想自己执行此操作:

public static String capitalize(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
        return str;
    }
    return new StringBuffer(strLen)
        .append(Character.toTitleCase(str.charAt(0)))
        .append(str.substring(1))
        .toString();
}

You could also try using this method: 您也可以尝试使用此方法:

 public static String capitalize(String str) { str = (char) (str.charAt(0) - 32) + str.substring(1); return str; } 


Though it should be noted that this method assumes that the first character in str is indeed a lowercase letter. 虽然应该注意这个方法假设str中的第一个字符确实是一个小写字母。

Finally, I tried to do it without stringutils.. But anyways, thanks to all who helped :) 最后,我尝试没有stringutils这样做..但无论如何,感谢所有谁帮助:)

public class Hello
    {
      public static void main(String[] args){
        String a = "steve";
        String b = "Andrew";
        String firstletter = a.substring(0,1);
        String remainder = a.substring(1);
        String capitalized = firstletter.toUpperCase() + remainder.toLowerCase();

        System.out.print("Hello " + capitalized + " " + b + "s" );

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM