0

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?

4
  • 2
    It's really not clear why you don't want to just use \r\n. It's also unclear what the first part of the question has to do with the second... Commented Jul 16, 2012 at 22:39
  • stackoverflow.com/questions/3613759/x-escape-in-java Commented Jul 16, 2012 at 22:39
  • Look to Java's StringBuilder class for a class which is cheap to modify as a String. Commented Jul 16, 2012 at 22:39
  • Sorry all, I edited the question. Is there a way to initialize a char array with a literal string constant? I will look into StringBuilder, that sounds promising. Commented Jul 16, 2012 at 22:42

2 Answers 2

2

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[]).

Sign up to request clarification or add additional context in comments.

2 Comments

Strings are immutable so I cannot use the String class.
@Batdude: You can convert between String and char[].
1

Use String.ToCharArray:

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

You could also use a StringBuilder which is mutable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.