#Help with Formatting Special Characters as New Lines in Java Code

1 messages · Page 1 of 1 (latest)

violet currentBOT
#

<@&987246399047479336> please have a look, thanks.

rich belfry
#

couldn't you just use .replace("\\n", "\n"), java knows the escape sequences

stone furnace
#

The problem is relatively simple:
When you read \f then that's 2 characters. The first is the \ character and the latter is the f character.
If you do "\n" in Java then that's a String of length 1, because here the \ is an escape character that gives the following n a special meaning.
This is also why you can write '\n', but you can't e.g. write '!n' (because the former would be a single character literal, while the latter would be a 2-letter character literal).

#

And yes, what @rich belfry suggested is exactly what you need to do in order to solve your issue

rich belfry
#

replaceAll("[\r\f\v]+", " \n")
the reader reads \r like Monke said as two characters exactly like there are in the input, so when it is converted to a java sting it is masked with a \ so there is \\r not \r in your string

stone furnace
# rich belfry > ` replaceAll("[\r\f\v]+", " \n")` the reader reads `\r` like Monke said as two...

when it is converted to a java sting it is masked with a \
Well, that's not really what happens.
There is no magical additional \ that appears out of thin air. This additional \ is purely so that we can write these character with special meaning and since \ itself has a special meaning (that is it's the escape character) Java wouldn't be sure what to do if we only wrote "\"
But there is no second character, this is simply a notation for humans. The computer wouldn't have a problem just working with numbers.

C makes this a lot clearer, because there characters are literally just integers, i.e. we can write:

char newline = '\n';
char newline_ascii = 10;

char lower_a = 'a';
char lower_a_ascii = 97;

printf("newline: |%c|\n" "newline_ascii: |%c|\n" "lower_a: |%c|\n" "lower_a_ascii: |%c|\n", newline, newline_ascii, lower_a, lower_a_ascii);
```and if you were to execute that code you'd get this output:

newline: |
|
newline_ascii: |
|
lower_a: |a|
lower_a_ascii: |a|

rich belfry
#

ok true. thinking of \n as one character is better and correct i had this "getting masked" as a mnemonic bridge, becuase you always work with \in the code