Append a single character to a string or char array in java?

前端 未结 7 1045
轻奢々
轻奢々 2020-12-13 17:31

Is it possible to append a single character to the end of array or string in java

for example:

    private static void /*methodName*/ () {                


        
相关标签:
7条回答
  • 2020-12-13 17:43
    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);
       }
      }
    

    Here's the output you'll get.

    * Enter a string CAT The new string is TCATT *

    It prints the the last character of the string to the first and last place. You can do it with any character of the String.

    0 讨论(0)
  • 2020-12-13 17:46
    new StringBuilder().append(str.charAt(0))
                       .append(str.charAt(10))
                       .append(str.charAt(20))
                       .append(str.charAt(30))
                       .toString();
    

    This way you can get the new string with whatever characters you want.

    0 讨论(0)
  • 2020-12-13 17:46

    And for those who are looking for when you have to concatenate a char to a String rather than a String to another String as given below.

    char ch = 'a';
    String otherstring = "helen";
    // do this
    otherstring = otherstring + "" + ch;
    System.out.println(otherstring);
    // output : helena
    
    0 讨论(0)
  • 2020-12-13 17:54

    First of all you use here two strings: "" marks a string it may be ""-empty "s"- string of lenght 1 or "aaa" string of lenght 3, while '' marks chars . In order to be able to do String str = "a" + "aaa" + 'a' you must use method Character.toString(char c) as @Thomas Keene said so an example would be String str = "a" + "aaa" + Character.toString('a')

    0 讨论(0)
  • 2020-12-13 17:57

    You'll want to use the static method Character.toString(char c) to convert the character into a string first. Then you can use the normal string concatenation functions.

    0 讨论(0)
  • 2020-12-13 18:00
    1. String otherString = "helen" + character;
    
    2. otherString +=  character;
    
    0 讨论(0)
提交回复
热议问题