Java character to String
我尝试了多种版本,包括在StackOverflow上找到的几种解决方案,但我总是得到数字而不是控制台中的字符。对于我大学的作业,我们需要把字符串中的字符颠倒过来。但创建新字符串似乎并不容易。
我试过用一个线生成器,
1 2 3 | StringBuilder builder = new StringBuilder(); // ... builder.append(c); // c of type char |
字符串串联,
1 |
和偶数字符串.valueof(),
它们中的每一个都有明确的转换成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | /** * Praktikum Informatik - IN0002 * Arbeitsblatt 02 - Aufgabe 2.6 (Buchstaben invertieren) */ public class H0206 { public static String readLine() { final StringBuilder builder = new StringBuilder(); try { // Read until a newline character was found. while (true) { int c = System.in.read(); if (c == ' ') break; builder.append(c); } } catch (java.io.IOException e) { ; // We assume that the end of the stream was reached. } return builder.toString(); } public static void main(String[] args) { // Read the first line from the terminal. final String input = readLine(); // Create a lowercase and uppercase version of the line. final String lowercase = input.toLowerCase(); final String uppercase = input.toUpperCase(); // Convert the string on the fly and print it out. for (int i=0; i < input.length(); ++i) { // If the character is the same in the lowercase // version, we'll use the uppercase version instead. char c = input.charAt(i); if (lowercase.charAt(i) == c) c = uppercase.charAt(i); System.out.print(Character.toString(c)); } System.out.println(); } } |
我看到您提供的示例代码存在以下问题:
1 2 3 4 5 |
将调用方法StringBuilder.Append(int)。正如javadoc所说,"总体效果就像参数被方法string.valueof(int)转换为字符串,然后将该字符串的字符附加到这个字符序列中一样。"这样将整数值强制转换为char将导致所需的行为:
1 2 3 4 5 |
1 2 3 4 5 6 7 | try { // Read until a newline character was found. while (true) { int c = System.in.read(); if (c == ' ') break; builder.append(c); } |
从你提供的样品中,我可以看出这是导致问题的原因。因为您将
在公共最终类StringBuilder中,您调用
1 2 | char ch = (char)c; builder.append(ch) |
如果需要,这会将c保留为整数,并在需要时将其"原始值"(在转换为
下面是一个如何反转字符串的示例,还有另外一个选项,我认为这一个更具教学意义。
1 2 3 4 5 6 7 8 9 10 11 | public static void main(final String[] args) { String text ="This is a string that will be inverted"; char[] charArray = text.toCharArray(); char[] invertedCharArray = new char[charArray.length]; for (int i = 1; i <= charArray.length; i++) { char c = charArray[charArray.length - i]; invertedCharArray[i - 1] = c; } System.out.println(text); System.out.println(new String(invertedCharArray)); } |