tags:

views:

57

answers:

5

Hi.

Tried searching in the Java String API with no answer.

I am trying to create Java strings with a specified size. I noticed that Java Strings do not end in the null character (\0). Basically, I would like to be able to create strings such as:

String myString = new String("Charles", 32);

where myString will contain "Charles <-- 24 spaces --> \0"

There is no such method that can achieve what I have above. Should I just rely on creating my own function to do so?

Thanks

A: 

Yeah, there probably isn't a built in function for that. You could pad the string to the required length using String.format() and then append a \0 to the end of it - that should do what you want fairly easily.

Alex Zylman
+2  A: 

Strings in Java are immutable. If you want those extra spaces at the end, you're simply going to have to create a string that contains those spaces.

Kirk Woll
+4  A: 
String myString = String.format("%1$-" + 32 + "s", "Charles");
Adam
Nice solution. Didn't think of that possibility.
Johannes Wachter
what is the "s" argument?
Carlo del Mundo
@Carlo - Null safety, if "Charles" was replaced with null, it will print the word null instead of giving a Null Pointer Exception
Adam
A: 

If you want to be able to work with fixed size strings in a mutable way, you could also write your own wrapper that encapsulates a presized char[], e.g.

public class MyString()
 private char[] values;

 public MyString(int size)
 {
   values=new char[size];
 }

 ... methods to set, get

 public String toString() { return new String(values);}
}
Steve B.
A: 

I would you one of the formatting options provided by Java to accomplish that.

For example implement your own java.text.Format implementation.

Another possibility would be to use a StringBuffer/StringBuilder with the specified capacity and initialize it with spaces and the \0. Then you can fiddle with the char positions when writing/modifying the text.

Johannes Wachter