0

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?

1
  • Will your final sentence always contain alphabets? Commented Aug 27, 2021 at 5:53

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Please explain the regex pattern and the answer is perfect.
@JoopEggen I have added a description for this code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.