将字符串值转换为ASCII

huangapple go评论75阅读模式
英文:

Convert a String Value to ASCII

问题

我想获取一个ASCII值(保存为字符串)并将其转换为字符以显示消息。我尝试了这个方法,但在声明int b时一直报告索引超出范围的错误。它还显示str和b没有值。

String value = "104 101 108 108 111";

char[] ch = new char[value.length()];
for (int i = 0; i < value.length(); i++) {
    ch[i] = value.charAt(i);
}
System.out.println(ch.length);
String ans = "";
int i = 0;
while (i+2 < ch.length) {
    int b = ch[i] + ch[i+1] + ch[i+2];
    String str = new Character((char) b).toString();
    System.out.println(str);
    System.out.println(b);
    ans = ans + str;
    i = i + 3;
}
英文:

I want to take the value of a ASCII value(Saved as a string) and convert it to the character to reveal a message. I tried this and it keeps throwing an index out of bound at the declaration of the int b.It also shows that str and b do not have a value

String value = "104 101 108 108 111";

    char[] ch = new char[value.length()];
    for (int i = 0; i &lt; value.length(); i++) {
        ch[i] = value.charAt(i);
    }
    System.out.println(ch.length);
    String ans = &quot;&quot;;
    int i = 0;
    while (i+2 &lt; ch.length) {
       
        
        int b= ch[i]+ch[i++]+ch[i+2];
        String str = new Character((char) b).toString();
        System.out.println(str);
        System.out.println(b);
    ans = ans+str;
    i=i+3;
    }

答案1

得分: 2

使用字符串分割函数

	String value = "104 101 108 108 111";

	String[] arrOfStr = value.split(" "); 
	
	String ans = "";

	for(String str : arrOfStr) {
		 String str1 = Character.toString((char)Integer.parseInt(str));
         ans += str1;
	}
	
	System.out.println(ans); // 输出:hello
英文:

Using string split function

	String value = &quot;104 101 108 108 111&quot;;

	String[] arrOfStr = value.split(&quot; &quot;); 
	
	String ans = &quot;&quot;;

	for(String str : arrOfStr) {
		 String str1 = Character.toString((char)Integer.parseInt(str));
         ans += str1;
	}
	
	System.out.println(ans); // output: hello

答案2

得分: 0

我们可以使用Java 8的Streams将“Imperative”代码切换为“Declarative”代码。

需要注意的关键点:

  1. 声明式风格更易读且更易编写。
  2. 字符串连接器比简单的字符串拼接更快。
  3. 无需编写迭代器。
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        String value = "104 101 108 108 111";

        Arrays.stream(value.split(" ")) // Starting a stream of String[]
            .mapToInt(Integer::parseInt) // mapping String to int
            .mapToObj(Character::toChars) // finding ASCII char from int
            .forEach(System.out::print); // printing each character
    }

}

如果您希望将结果存储起来然后打印出来,可以按照以下方式进行操作。

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String value = "104 101 108 108 111";

        String result = Arrays.stream(value.split(" ")) // Starting a stream of String[]
                            .mapToInt(Integer::parseInt) // mapping String to int
                            .mapToObj(Character::toChars) // finding ASCII char from int
                            .map(String::new) // convert char to String
                            .collect(Collectors.joining()); // combining individual result using String Joiner

        System.out.println(result);
    }

}
英文:

We can switch the Imperative code to Declarative code using Java 8 Streams.

Key points to observe:

  1. Declarative style is more readable and easy to write.
  2. String Joiner is faster than simple String Concatenation.
  3. No need to write an iterator.
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        String value = &quot;104 101 108 108 111&quot;;

        Arrays.stream(value.split(&quot; &quot;)) // Starting a stream of String[]
            .mapToInt(Integer::parseInt) // mapping String to int
            .mapToObj(Character::toChars) // finding ASCII char from int
            .forEach(System.out::print); // printing each character
    }

}

If you wish to store the result and then print it, this is how is done.

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String value = &quot;104 101 108 108 111&quot;;

        String result = Arrays.stream(value.split(&quot; &quot;)) // Starting a stream of String[]
                            .mapToInt(Integer::parseInt) // mapping String to int
                            .mapToObj(Character::toChars) // finding ASCII char from int
                            .map(String::new) // convert char to String
                            .collect(Collectors.joining()); // combining individual result using String Joiner

        System.out.println(result);
    }

}

答案3

得分: -1

// 代码注释:

// 有一个内置方法可以获得字符串的字符数组 `char[]`,因此下面这两个代码块是相同的:

```lang-java
// 来自问题的代码
char[] ch = new char[value.length()];
for (int i = 0; i < value.length(); i++) {
    ch[i] = value.charAt(i);
}

// 使用内置方法
char[] ch = value.toCharArray();

在循环时递增一个值时最好使用 for 循环。下面两种方式的循环行为相同,但 for 循环将循环逻辑放在一起:

// 来自问题的代码
int i = 0;
while (i+2 < ch.length) {
    // 这里有一些代码
    i=i+3;
}

// 使用 for 循环
for (int i = 0; i + 2 < ch.length; i=i+3) {
    // 这里有一些代码
}

下面这行代码是完全错误的:

int b= ch[i]+ch[i++]+ch[i+2];
  1. i++ 递增了 i 的值,但在表达式中使用的是递增前的值,这意味着如果在此行之前 i = 0,结果与以下代码相同:

    int b = ch[0] + ch[0] + ch[2];
    i = i + 1;
    

    您需要用 i + 1 替换 i++,并意识到它们是不同的

  2. 由于您不再在该语句中将 i 的值递增 1,因此循环必须从 i=i+3 更改为 i = i + 4,以正确跳过输入中的空格。

  3. ch[i] 的值是一个 char 值,通过使用 + 运算符将其扩展为 int 值。charint 值是 Unicode 代码点值,对于您的文本,它也是字符的 ASCII 码。

    这意味着如果 i = 0,在修复问题#1后,表达式将计算为:

    int b = ch[0] + ch[1] + ch[2];
    
    int b = `1` + `0` + `4`;
    
    int b = 49 + 48 + 52;
    
    int b = 149;
    

    这与在问题中运行代码的输出相匹配,其中第二个打印的数字是 149(在修复问题#1后)。

您真正想要的是获取子字符串 &quot;104&quot;,将其转换为数字,然后将该 ASCII 码值强制转换为 char,就像这样:

String numberStr = value.substring(i, i + 3); // 例如:&quot;104&quot;
int number = Integer.parseInt(numberStr);     // 例如:104
String str = String.valueOf((char) number);   // 例如:&quot;h&quot;

有了这个,您就不再需要 char[],因此最终的代码将是:

String value = &quot;104 101 108 108 111&quot;;

String ans = &quot;&quot;;
for (int i = 0; i + 2 < value.length(); i += 4) {
    String numberStr = value.substring(i, i + 3);
    int number = Integer.parseInt(numberStr);
    String str = String.valueOf((char) number);
    ans = ans + str;
}
System.out.println(ans);

输出

hello
英文:

Comments to code:

There is a built-in method for for getting a char[] with the characters of a string, so the following two blocks of code are the same:

// Code from question
char[] ch = new char[value.length()];
for (int i = 0; i &lt; value.length(); i++) {
    ch[i] = value.charAt(i);
}

// Using built-in method
char[] ch = value.toCharArray();

It is better to use a for loop when increment a value while looping. The following two ways of writing the loop behave the same, but the for loop keeps the loop logic together:

// Code from question
int i = 0;
while (i+2 &lt; ch.length) {
    // some code here
    i=i+3;
}

// Using for loop
for (int i = 0; i + 2 &lt; ch.length; i=i+3) {
    // some code here
}

The following line of code is entirely wrong:

int b= ch[i]+ch[i++]+ch[i+2];
  1. i++ increments the value is i, but it is the value before the increment that is used in the expression, which means that if i = 0 before the line, the result is the same as this code:

    int b = ch[0] + ch[0] + ch[2];
    i = i + 1;
    

    You need to replace i++ with i + 1, and realize that those are not the same.

  2. Since you no longer increment the value of i by 1 in that statement, the loop much be changed from i=i+3 to i = i + 4, to correctly skip the spaces in the input.

  3. The value of ch[i] is a char value, which is widened to an int value by the use of the + operator. The int value of a char is the Unicode Code Point value, which for your text is also the same as the ASCII code for the character.

    This means that if i = 0, the expression would (after fixing issue #1) evaluate as:

    int b = ch[0] + ch[1] + ch[2];
    
    int b = `1` + `0` + `4`;
    
    int b = 49 + 48 + 52;
    
    int b = 149;
    

    That matches the output from running the code is in question, where the second printed number is 149 (after fixing issue #1).

What you really wanted was to get the substring &quot;104&quot; and convert that to a number, then cast that ASCII code value to a char, like this:

String numberStr = value.substring(i, i + 3); // E.g. &quot;104&quot;
int number = Integer.parseInt(numberStr);     // E.g. 104
String str = String.valueOf((char) number);   // E.g. &quot;h&quot;

With that, you no longer need the char[], so the final code would be:

String value = &quot;104 101 108 108 111&quot;;

String ans = &quot;&quot;;
for (int i = 0; i + 2 &lt; value.length(); i += 4) {
	String numberStr = value.substring(i, i + 3);
	int number = Integer.parseInt(numberStr);
	String str = String.valueOf((char) number);
	ans = ans + str;
}
System.out.println(ans);

Output

hello

huangapple
  • 本文由 发表于 2020年7月26日 02:01:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63091745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定