gpt4 book ai didi

Java字符转字符串

转载 作者:行者123 更新时间:2023-12-02 05:19:56 26 4
gpt4 key购买 nike

我尝试了多个版本,包括在 StackOverflow 上找到的几个解决方案,但我总是在控制台中得到数字而不是字符。对于我大学的作业,我们需要反转字符串中的字符。但创建新字符串似乎并不那么容易。

我尝试使用 StringBuilder,

StringBuilder builder = new StringBuilder();
// ...
builder.append(c); // c of type char

字符串连接,

System.out.print("" + c); // c of type char

甚至 String.valueOf(),

System.out.print(String.valueOf(c)); // c of type char

并且它们中的每一个都再次显式转换为char。但我总是得到序列中字符的序号,而不是控制台中输出的实际字符。如何正确地从 char 构建新字符串?

/**
* 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 == '\n')
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();
}

}

最佳答案

我在您提供的示例代码中发现的问题如下:

int c = System.in.read();
if (c == '\n')
break;
builder.append(c);

调用方法的方式,Stringbuilder.append(int)将被调用。正如 javadoc 所说,“总体效果就像通过 String.valueOf(int) 方法将参数转换为字符串,然后将该字符串的字符附加到该字符序列”。像这样将整数值转换为 char 将产生所需的行为:

int c = System.in.read();
if (c == '\n')
break;
builder.append((char) c);

关于Java字符转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26591171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com