我尝试了多个版本,包括在StackOverflow上找到的几个解决方案,但我总是获取数字而不是控制台中的字符。对于我的uni中的作业,我们需要反转字符串中的字符。但创建新的字符串似乎并不那么容易。Java字符到字符串
我试图用一个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
s建立一个新的字符串?
/**
* 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();
}
}
'char'类型的'c'?我在你的例子中看到的是一个'int'。另外,'System.in.read()'做了什么? – 2014-10-27 15:36:16
['String#valueOf()'shoud work](http://stackoverflow.com/questions/8172420/how-to-convert-a-char-to-a-string-in-java)...你是否确定你的角色不是数字,例如''4''? – sp00m 2014-10-27 15:38:24
'c'可以保存一个字符数据,但肯定是'int'类型而不是'char'。像这样将它转换为char:'char ch =(char)c;'。 – icza 2014-10-27 15:40:18