【问题标题】:How to convert ASCII values that are substring inside a string to its character如何将字符串中的子字符串的 ASCII 值转换为其字符
【发布时间】:2021-08-27 16:49:40
【问题描述】:

如何将字符串中的子字符串的 ASCII 值转换为其字符?例如:

如果我输入为

H105 68u100e33 65r101 89o117?

我需要输出为

Hi Dude! How Are You?

在上面的输入中,每个字母或空格后面都有一个 ASCII 值。

char[] a = new char[2];
char t;
String temp,output="";

for(int i=0;i<str.length()-1;i++){
    a[0]=str.charAt(i);
    a[1]=str.charAt(i+1);
    if(Character.isDigit(a[0])){
        if(Character.isDigit(a[1])){
            String con=String.valueOf(a[0])+String.valueOf(a[1]);
            int n=Integer.parseInt(con);
            output=output+(char)n;
        }else{
            //nothing
        }
    }else{
        output=output+a[0];
    }
}

System.out.println("output : "+output);

我尝试过类似的方法,但它在 3 位 ASCII 值时失败,而且有时由于charAt(i+1) 语句,我会遇到数组索引出站错误。

如何将 ASCII 值更改为它的字符并形成一个句子?

【问题讨论】:

  • 你的最后一句话总是包含字母吗?

标签: java


【解决方案1】:

您必须根据短语“首先获取所有数字,然后为每个数字,将其替换为其 ASCII 值”来创建算法

所以,

public static void main(String[] args)
{
    String input = "H105 68u100e33 65r101 89o117?";
    
    // Get all the digits by replacing the non-digits with space
    // And then split the string with space char to get them as array
    final String[] digits = input.replaceAll("\\D+"," ").trim().split(" ");
    
    // For each one, replace the main input with the ascii value
    for (final String digit : digits)
        input = input.replaceAll(digit, Character.toString(Integer.parseInt(digit)));
    
    System.out.println(input);
}

【讨论】:

    【解决方案2】:

    试试这个。

    static final Pattern NUM = Pattern.compile("\\d+");
    
    public static void main(String[] args) {
        String input = "H105 68u100e33 65r101 89o117?";
        String output = NUM.matcher(input)
            .replaceAll(m -> Character.toString(Integer.parseInt(m.group())));
        System.out.println(output);
    }
    

    输出:

    Hi Dude! Are You?
    

    NUM 是匹配一个或多个数字的模式。
    NUM.matcher(input).replaceAll() 替换input 中与此模式匹配的所有字符。
    m-&gt; Character.toString(Integer.parseInt(m.group())) 将匹配的数字字符串转换为整数,然后转换为与该字符代码对应的字符串。

    【讨论】:

    • 请解释正则表达式模式,答案很完美。
    • @JoopEggen 我已经为这段代码添加了描述。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 2010-12-09
    相关资源
    最近更新 更多