2013-01-21 119 views
32

是否有可能单个字符追加到数组或字符串中的Java将单个字符追加到java中的字符串或char数组中?

末例如:

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

我已经尝试过追加法,但是我对如何使用它非常困惑...... – CodeLover

+3

所以*你怎么试着使用append方法?你有没有试过简单的字符串连接通过+?请注意,字符串和数组是完全不同的东西... –

+0

@CodeLover ..你检查了String类的文档吗?它没有任何'append'方法。 Google用于'Java中的字符串串联'。也许你可以得到一些想法 –

回答

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

2. otherString += character; 
0

只需添加它们是这样的:

 String character = "a"; 
     String otherString = "helen"; 
     otherString=otherString+character; 
     System.out.println(otherString); 
+0

因为相同的答案已经存在 – 2016-11-17 06:50:41

+0

因此-1 .... – 2016-11-17 06:50:59

3

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

3

首先,你在这里使用两个字符串:“”标志着一个字符串,它可能是"" -empty "s" - lenght 1或"aaa"串lenght 3的字符串,而“”标记字符。为了能够做到String str = "a" + "aaa" + 'a'您必须使用方法Character.toString(焦三)为@Thomas基恩是这么说的一个例子是String str = "a" + "aaa" + Character.toString('a')

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 *

它打印字符串的第一个和最后一个地方的最后一个字符。你可以用任何字符串来完成它。

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

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

相关问题