2013-01-21 22 views
32

E 'possibile per aggiungere un singolo carattere alla fine di array o stringhe in JavaAggiungi un singolo carattere a una stringa o array di caratteri in java?

ad esempio:

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

ho provato il metodo append ma sono molto confuso su come usarlo ... – CodeLover

+3

Quindi * come * hai provato ad usare il metodo append? E hai provato una semplice concatenazione di stringhe tramite +? Nota che le stringhe e gli array sono cose completamente diverse ... –

+0

@CodeLover .. Hai controllato la documentazione della classe 'String'. Non ha alcun metodo 'append'. Google per 'String Concatenation in Java'. Può essere che tu possa avere un'idea –

risposta

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

2. otherString += character; 
0

basta aggiungere in questo modo:

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

perché la stessa risposta esiste già –

+0

Pertanto -1 .... –

3

È 'Voglio usare il metodo statico Character.toString (char c) per convertire prima il personaggio in una stringa. Quindi è possibile utilizzare le normali funzioni di concatenazione delle stringhe.

3

Prima di tutto si usano qui due stringhe: "" segna una stringa può essere "" -empty "s" - stringa di lunghezza 1 o "aaa" stringa di lunghezza 3, mentre '' denota caratteri. Al fine di essere in grado di fare String str = "a" + "aaa" + 'a' è necessario utilizzare il metodo Character.toString (char c) come ha detto @Thomas Keene così un esempio potrebbe essere 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); 
    } 
    } 

Ecco l'output che si ottengono.

* inserire una stringa CAT La nuova stringa è TCATT *

Esso stampa il l'ultimo carattere della stringa per il primo e l'ultimo posto. Puoi farlo con qualsiasi personaggio della String.

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

In questo modo è possibile ottenere la nuova stringa con qualsiasi carattere desiderato.

Problemi correlati