0

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

3
  • 1
    No need for [] after String, although you can use char[] similarly to String (still doesn't require a NUL terminator). Commented Aug 11, 2010 at 17:38
  • The above Java code declares an array of strings, but assigns it a single string as its value. You should probably edit the example to clarify your question. Commented Aug 11, 2010 at 17:39
  • The code you posted will not compile, because you declared myString as an array of String s, but then you assign a single String object to it. Commented Aug 11, 2010 at 17:41

5 Answers 5

3
String myString = String.format("%1$-" + 32 + "s", "Charles");
Sign up to request clarification or add additional context in comments.

2 Comments

Nice solution. Didn't think of that possibility.
@Carlo - Null safety, if "Charles" was replaced with null, it will print the word null instead of giving a Null Pointer Exception
2

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.

Comments

0

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.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.