简体   繁体   English

将String转换为ASCII并将ASCII转换为String

[英]convert String to ASCII and ASCII to String

This is my code to convert String to ASCII and ASCII to String. 这是我的将String转换为ASCII并将ASCII转换为String的代码。 I have problem when the user enter text with spaces the all texts didn't convert but if i wrote the text in program the text converted . 当用户用空格输入文本时,所有文本均未转换,但是如果我在程序中编写了文本,则转换后的文本会出现问题。 This is my input "Java is easy" 这是我的输入“ Java很简单”

String str = input.next();
//String str = "Java is easy";

char ch[] = str.toCharArray();
int num[] = new int[str.length()];

for (int i = 0; i < str.length(); i++) {
    System.out.print((int)ch[i] + " ");
    num[i] = (int)ch[i];
}
System.out.println("");
for (int j = 0; j < str.length(); j++) {
    System.out.print((char)num[j]);
}
System.out.println("");

Scanner.next() reads a single word, ie "Java". Scanner.next()读取一个单词,即“ Java”。

Scanner.nextLine() reads an entire line, ie "Java is easy" Scanner.nextLine()读取整行,即“ Java很简单”

You should change 你应该改变

String str = input.next();

to

String str = input.nextLine();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM