Badcoder
Badcoder

Reputation: 23

How to convert ASCII values that are substring inside a string to its character

How to convert ASCII values that are substring inside a string to its character? For example:

If I give input as

H105 68u100e33 65r101 89o117?

I need output as

Hi Dude! How Are You?

In the above input after every alphabet or spaces there is an ASCII value.

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);

I have tried something like this, and it fails at 3 digit ASCII values and also sometimes I face array index outofbound error due to charAt(i+1) statements.

How to change that ASCII values to its char and form a sentence?

Upvotes: 0

Views: 139

Answers (2)

user4910279
user4910279

Reputation:

Try this.

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);
}

output:

Hi Dude! Are You?

NUM is a pattern that matches one or more digits.
NUM.matcher(input).replaceAll() replaces all characters that match this pattern in input.
m-> Character.toString(Integer.parseInt(m.group())) converts the matched numeric string to an integer and then converts to the string corresponding to that character code.

Upvotes: 1

Melron
Melron

Reputation: 579

You have to create your algorithm based on the phrase "Get all the digits first, and then for each one, replace it with its ASCII value"

So,

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);
}

Upvotes: 1

Related Questions