Saya
Saya

Reputation: 302

What is the best way to replace all special characters with their full names in a String Java?

I want to convert all the special characters in a String to their full names.

Example:

Input: What is stack overflow?

Output: What is stack overflow question mark

I used replaceall() to do it, but is there any simpler way of doing it because I have to write one line for each special character?

text = text.replaceAll("\\.", " Fullstop ");
text = text.replaceAll("!", " Exclamation mark ");
text = text.replaceAll("\"", " Double quote ");
text = text.replaceAll("#", " Hashtag ");
...

Upvotes: 2

Views: 1034

Answers (5)

Kaplan
Kaplan

Reputation: 3738

using an IntStream allows to do it in one swoop

String text= "Input: What is stack overflow?";
System.out.println(
    text.codePoints().mapToObj( c -> {
      switch( c ) {
      case '.':
        return "‹Fullstop›";
      case '!':
        return "‹Exclamation mark›";
      case '"':
        return "‹Double quote›";
      case '#':
        return "‹Hashtag›";
      case '?':
        return "‹Question mark›";
      default:
        return String.valueOf( (char)c );
      }
    } ).collect( StringWriter::new, StringWriter::write,
        ( w1, w2 ) -> w1.write( w2.toString() ) ).toString() );

…or adapted with Joop Eggen's idea (but keeping the original text)

System.out.println(
    text.codePoints().collect( StringWriter::new,
        (w, c) -> w.write( Character.isAlphabetic( c )
            ? Character.toString( c ) : '‹' + Character.getName( c ) + '›'),
        ( w1, w2 ) -> w1.write( w2.toString() ) ).toString() );

gets: Input‹COLON›‹SPACE›What‹SPACE›is‹SPACE›stack‹SPACE›overflow‹QUESTION MARK›

Upvotes: 0

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79115

You can do it in a single statement.

You can chain the string operations i.e. the result of one string operation can be passed to the next operation by chaining as shown below:

public class Main {
    public static void main(String[] args) {
        String text = "He asked, \"What is Stackoverflow?\"\nHow beautiful!\nNeither am I the God nor am I the Devil.";
        
        text = text.replaceAll("\\.", " Fullstop ")
                .replaceAll("!", " Exclamation mark ")
                .replaceAll("\"", " Double quote ")
                .replaceAll("#", " Hashtag ");
        
        System.out.println(text);
    }
}

Output:

He asked,  Double quote What is Stackoverflow? Double quote 
How beautiful Exclamation mark 
Neither am I the God nor am I the Devil Fullstop 

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109577

Look at built-in Unicode names:

    String s = "a!\".";
    s.codePoints()
            .filter(cp -> !Character.isAlphabetic(cp))
            .forEach(cp -> System.out.println(Character.getName(cp)));

EXCLAMATION MARK
QUOTATION MARK
FULL STOP

With a toLowerCase/capitalize you can have a fine complete & compact result.

Upvotes: 1

Alberto
Alberto

Reputation: 12939

You can use Stream:

String text= "Input: What is stack overflow?";
HashMap<String, String> map = new HashMap<String, String>(){{
    put("\\.", " Fullstop ");
    put("!", " Exclamation mark ");
    put("\"", " Double quote ");
    put("#", " Hashtag ");
    put("?", " question mark");
}};
System.out.println(
        Stream.of(text.split(""))
                .map(s -> map.getOrDefault(s,s))
                .collect(Collectors.joining())
);

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521639

One approach here would be to maintain a hashmap containing all symbols and their name replacements. Then, do a regex iteration over the input string and make all replacements.

Map<String, String> terms = new HashMap<>();
terms.put(".", " Fullstop ");
terms.put("!", " Exclamation mark ");
terms.put("\"", " Double quote ");
terms.put("#", " Hashtag ");

String input = "The quick! brown #fox \"jumps\" over the lazy dog.";
Pattern pattern = Pattern.compile("[.!\"#]");
Matcher matcher = pattern.matcher(input);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
    matcher.appendReplacement(buffer, terms.get(matcher.group(0)));
}
matcher.appendTail(buffer);

System.out.println("input:  " + input);
System.out.println("output: " + buffer.toString());

This prints:

input:  The quick! brown #fox "jumps" over the lazy dog.
output: The quick Exclamation mark  brown  Hashtag fox  Double quote jumps Double quote  over the lazy dog Fullstop 

The above approach appears a bit verbose, but in practice all the core replacement logic is happening within a one line while loop. If you are on Java 8, you could also use a Matcher stream approach, but the logic would be more or less the same.

Upvotes: 2

Related Questions