I am an experienced C++ programmer but new to Java.
I have an algorithm that does some string manipulation and I want to terminate a string in the middle.
Say, I want to do something like this
String str("hello, world");
char[] str2 = str.toCharArray();
//pass str2 to some function
myFunc(str2);
...
//inside myFunc, I decide to terminate str2 at position 3, so I did
//str2[3] = 0
//then it returns, how can I construct an String type variable from str2 that includes chars before the '\0'?
//String str3 = new String(str2), doesn't work
I can write my own C-liked strlen. However I would like to know what is the elegant way of doing it in Java.
Also, it is hard to find document about type char[]. Whenever I Google, I can only find document on “char” instead of “char[]”. I am thinking char[] may have methods liked substr or strlen.
Thanks for any suggestion!
In Java,
char[]andStringare completely different. Forget the association from C, As far as you’re concerned for now, they’re not connected in any way. (For completeness, thatStringobjects hold afinal char[]representing the string (and it’s not null-terminated), which you can obtain as you did in your example. Don’t do that until you’re clear on the difference.) You call all your methods on the string. But remember, in Java,Strings are immutable – if you have a String, it will always be the same. You can assign a new String object to a variable, but the old string won’t change (until all references are gone and it gets GC’d, of course). This is important to remember when you are trying to get a new string, like this. Once you’ve figured out how long you want your string, use.substring().So your example should look something like this: