繁体   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