簡體   English   中英

在java中將單個字符附加到字符串或字符數組?

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

是否可以在java中將單個字符附加到arraystring的末尾? 例子:

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. String otherString = "helen" + character;

2. otherString +=  character;

您需要先使用靜態方法 Character.toString(char c) 將字符轉換為字符串。 然后你可以使用普通的字符串連接函數。

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

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

首先,您在這里使用兩個字符串: "" 標記一個字符串,它可能是"" -empty "s" - 長度為 1 的字符串或長度為 3 的"aaa"字符串,而 '' 標記為 chars 。 為了能夠執行String str = "a" + "aaa" + 'a'你必須使用方法 Character.toString(char c) 如@Thomas Keene 所說,所以一個例子是String str = "a" + "aaa" + Character.toString('a')

只需像這樣添加它們:

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

對於那些正在尋找何時必須將字符連接到字符串而不是將字符串連接到另一個字符串的人,如下所示。

char ch = 'a';
String otherstring = "helen";
// do this
otherstring = otherstring + "" + ch;
System.out.println(otherstring);
// output : helena
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 *

它將字符串的最后一個字符打印到第一個和最后一個位置。 您可以使用字符串的任何字符來執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM