繁体   English   中英

Java concat与整数和字符串

[英]Java concat with integer and string

我想编写一个程序,该程序将整数和字符串传递给值返回方法。 我知道如何做这部分,但是我需要将int(即2)和字符串(表示“ bye”)连接起来,并用字符串打印int的编号。 (例如:再见)。

我将尽快答复以澄清问题。

您可以在Java中将String与int连接起来,如下所示:

String result = "some " + 2;

该字符串应在此“ +”运算符中排在最前面。

试试这个

private String repeateAndConcateString (int prm_Repeat, String prm_wordToRepeat){
            if(prm_Repeat <=0 || prm_wordToRepeat == null){
                      return "";
             }
            String temp = "";
            for(int i= 1 ; i<=prm_Repeat ; i++){  // loop through the number of times to concatinate. 
                  temp += prm_wordToRepeat; //Concate the String Repeatly 1 to prm_Repeat 
             }
           return temp;   // this will return Concatinate String.
}

对于字符串重复, Apache StringUtils具有方法repeat

或没有外部的实现:

public static String repeat(int n, String s){
    StringBuilder sb = new StringBuilder(n * s.length());
    while(n--)
        sb.append(s);
    return sb.toString();
}

整数可以通过以下两个引用转换为字符串: String.valueOfInteger.toString 字符串连接的工作方式类似于数学加法( + )。

尝试这个。

static String repeat(int times, String s) {
    return IntStream.range(0, times)
        .mapToObj(x -> s)
        .collect(Collectors.joining(" "));
}

System.out.println(repeat(2, "bye"));
// -> bye bye
public String repeatString(String str, int n)
{
    if(n<1 || str==null)
        return str;
    StringBuilder sb = new StringBuilder();
    for(int i=0; i<n; i++)
    {
        sb.append(str);
        if(i!=(n-1))        // If not the last word then add space
            sb.append(" ");
    }
    return sb.toString();
}

暂无
暂无

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

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