Java - How to put special characters into a String

2020-05-06 17:08发布

Java seems to have very good string handling. Still, I'm having problems with the simplest of problems. I need to have dynamic strings (they change at run time) so a String type is not a good choice since they are immutable. So I am using char arrays. Kind of a pain to setup but at least they are modifiable. I want to create a string constant with a carriage return/line feed pair in it (or other control characters). In C/C++ you would just do this:

char myString[100];
myString = "This is a string with a CR/LF pair\x0D\x0A";

And yes, I know in java you could use a "\r". And yes, I know that you could use:

myString[34] = 0x000D;
myString[35] = 0x000A;

And in Java you really cannot use a string literal constant to initialize a char array (can you??). So how do you initialize a char array is the question?

标签: java
2条回答
在下西门庆
2楼-- · 2020-05-06 17:16

Use String.ToCharArray:

char[] chars = "This is a string\r\n".ToCharArray();

You could also use a StringBuilder which is mutable.

查看更多
Juvenile、少年°
3楼-- · 2020-05-06 17:19

You can do

char[] myString = 
   "This is a string with a CR/LF pair\u000D\u000A".toCharArray();

if that was the question.

Also, there is StringBuilder to work with mutable Strings (it just wraps a char[]).

查看更多
登录 后发表回答