user402642
user402642

Reputation:

Java String; Able to allocate the size of the string given a size?

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

Upvotes: 0

Views: 3887

Answers (5)

Johannes Wachter
Johannes Wachter

Reputation: 2735

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.

Upvotes: 0

Steve B.
Steve B.

Reputation: 57333

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);}
}

Upvotes: 0

Adam
Adam

Reputation: 44959

String myString = String.format("%1$-" + 32 + "s", "Charles");

Upvotes: 3

Kirk Woll
Kirk Woll

Reputation: 77606

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.

Upvotes: 2

Alex Zylman
Alex Zylman

Reputation: 920

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.

Upvotes: 0

Related Questions