在Java中如何向字符串或字符数组追加单个字符?

65

在Java中是否可以将单个字符附加到数组字符串的末尾。例如:

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?               
}

1
我已经尝试过使用append方法,但我非常困惑如何使用它... - CodeLover
5
你尝试过怎样使用append方法?你尝试过通过加号进行简单的字符串拼接吗?请注意,字符串和数组是完全不同的东西。 - Jon Skeet
2
由于它们是字符串,您可以通过执行 otherString + character 来使用语言的内置字符串连接机制。 - fge
1
你正在考虑使用具有append方法的StringBuilder类。 - squiguy
10
请展示更多的研究努力。每次您忘记某些内容或想了解一些基础操作/方法时,不要在此处发表问题。 - keyser
显示剩余2条评论
7个回答

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

2. otherString +=  character;

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

9
new StringBuilder().append(str.charAt(0))
                   .append(str.charAt(10))
                   .append(str.charAt(20))
                   .append(str.charAt(30))
                   .toString();

通过这种方式,您可以获取包含任何字符的新字符串。


3

首先,你在这里使用了两个字符串:""表示一个字符串,它可以是"" - 空的"s" - 长度为1的字符串,或者"aaa" - 长度为3的字符串,而''标记字符。为了能够执行String str = "a" + "aaa" + 'a',你必须像@Thomas Keene所说的那样使用Character.toString(char c)方法,一个例子就是String str = "a" + "aaa" + Character.toString('a')


2
只需像这样添加它们:
        String character = "a";
        String otherString = "helen";
        otherString=otherString+character;
        System.out.println(otherString);

2

对于那些想要将char连接到String而不是将一个String连接到另一个String的人,可以使用以下方法:

char ch = 'a';
String otherstring = "helen";
// do this
otherstring = otherstring + "" + ch;
System.out.println(otherstring);
// output : helena

3
谢谢您的回答,但我建议您查看一下Java中的操作方式。接受的答案可以适用于变量名为'char'或'String'的情况,并且您答案中的空字符串:[otherstring + "" + ch]是不必要的。此外,我认为这个问题不需要另一个新答案,因为现有的答案已经提供了足够的覆盖范围。 - Elletlar
我回答了这个问题,因为如果你仔细看,你会发现问题标题有点模糊,并且与用户打算问的问题无关,我试图准确回答。干杯! - skmangalam
2
在这行代码中,添加一个空的 "" 是完全没有必要的:otherstring = otherstring + "" + ch; - Antroid

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 *
它将会打印出字符串的最后一个字符放在第一位和最后一位。你可以对任何字符串中的字符进行操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接