58

是否可以将单个字符附加到arrayjava.util string. 例子:

private static void /*methodName*/ () {            
    String character = "a"
    String otherString = "helen";
    //this is where i need help, i would like to make the otherString become 
    // helena, is there a way to do this?               
}
4

7 回答 7

115
1. String otherString = "helen" + character;

2. otherString +=  character;
于 2013-01-21T18:13:10.170 回答
11

您需要先使用静态方法 Character.toString(char c) 将字符转换为字符串。然后你可以使用普通的字符串连接函数。

于 2013-09-19T23:22:57.330 回答
9
new StringBuilder().append(str.charAt(0))
                   .append(str.charAt(10))
                   .append(str.charAt(20))
                   .append(str.charAt(30))
                   .toString();

这样你就可以得到你想要的任何字符的新字符串。

于 2016-10-13T12:19:34.510 回答
3

首先,您在这里使用两个字符串: "" 标记一个字符串,它可能是""-empty "s"- 长度为 1 "aaa"的字符串或长度为 3 的字符串,而 '' 标记 chars 。为了能够做到这一点,String str = "a" + "aaa" + 'a'您必须使用方法 Character.toString(char c) 正如@Thomas Keene 所说的,所以一个例子是String str = "a" + "aaa" + Character.toString('a')

于 2014-01-15T11:51:50.810 回答
2

只需像这样添加它们:

        String character = "a";
        String otherString = "helen";
        otherString=otherString+character;
        System.out.println(otherString);
于 2013-01-21T18:13:53.700 回答
1

对于那些正在寻找何时必须将 char 连接到 String 而不是将 String 连接到另一个 String 的人,如下所示。

char ch = 'a';
String otherstring = "helen";
// do this
otherstring = otherstring + "" + ch;
System.out.println(otherstring);
// output : helena
于 2018-07-28T17:50:08.703 回答
0
public class lab {
public static void main(String args[]){
   Scanner input = new Scanner(System.in);
   System.out.println("Enter a string:");
   String s1;
   s1 = input.nextLine();
   int k = s1.length();
   char s2;
   s2=s1.charAt(k-1);
   s1=s2+s1+s2;
   System.out.println("The new string is\n" +s1);
   }
  }

这是您将获得的输出。

* 输入字符串 CAT 新字符串为 TCATT *

它将字符串的最后一个字符打印到第一个和最后一个位置。您可以使用字符串的任何字符来执行此操作。

于 2015-03-24T05:18:19.883 回答