0

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!

2
  • 1
    Strings in Java are immutable. You can't modify them. They also don't have terminating characters. They also have no relation to arrays of type char. Commented Jan 16, 2012 at 4:56
  • Note, in particular, that \0 is a legal character within a Java string! Commented Jan 16, 2012 at 4:59

4 Answers 4

3

In Java, char[] and String are completely different. Forget the association from C, As far as you're concerned for now, they're not connected in any way. (For completeness, that String objects hold a final 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:

// Remember in Java no object is statically allocated.
String str1 = "Hello, World";
int indexToCutAt = myFunc(str1);
// We can't change str1, so we'll need to store the new string.
String str2 = str1.substring(0,indexToCutAt);
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, Kevin. I am aware of the points you mention. The reason I try to write a function to manipulate char[] is exactly because I read that String is immutable. I know I can return a String object, or an int as you suggest, and I think it is very good. I just want to make sure Java doesn't have a default method to construct a String by reading a NUL terminated char array.
@AlfredZhong Well the answer to that is no, Java doesn't use null-termination for anything including strings, because its arrays have lengths. You can either copy the chars to a new, shorter array or use substring.
Thanks again, Kevin. I thinking returning a String type substring directly will work but less memory efficient. Although I am aware Java does garbage collection, it uses more memory at some point. Returning and int seems requires exception for empty char array or array just has one element. I think returning the sbustring seems a better solution. What is you opinion? Please excuse that I am a geek...
@Alfred Yes, returning a substring from your method is probably easier. I don't think there will be a significant memory Impact either way though.
I changed my mind. I think returning the int is better although it seems a little bit cumbersome. When the size of the string has several billion, memory does matter.
3

Correct me if I'm wrong, but it looks like you're just trying to get the first three characters of the String. To do this, you can just do:

str.substring(0, 3);

char[] is not a class of its own. All arrays do have lengths, that you can retrieve as follows:

char[] myChars = new Char[5];
return myChars.length; // returns 5

However, you should just handle things as String objects, generally, and not char[]. String extends CharSequence which is (as the name would imply) just a sequence of char primitives, essentially being a char[].

tl;dr: Just use the String methods

6 Comments

The problem is that this "3" is calculated in "myFunc", and "myFunc" only set str[3] to 0. How can main get this information without writing a function to search for 0?
@Bon Espresso: It's actually the opposite; you don't have to pass an endIndex if you want it to go to the end of the String. You always need to specify beginIndex. See the documentation for details.
@Alfred Zhong: It's a bit difficult to determine without knowing the constraints/design of your classes, but you should be able to return "3" from myFunc, and use it in your substring call, e.g: str.substring(0, myFunc(str2)). What are you trying to accomplish?
@AlfredZhong, to determine the index that has been set to zero by myFunc, use String#indexOf
I wrote myFunc in C++, it handles char[], so I don't need to change much of it in Java. In C++, when returns from myFunc, it is very easy to construct a C++ std::string. I am just wondering how to do similar thing in java.
|
2

Use java substring method String#substring()

str3 = str.substring(0, 3);

Comments

2

Have a look at , substring(int beginIndex) and substring(int beginIndex, int endIndex) , This will help :)

So in your function myFunc(str2); return the position you want to break say pos ,

so you want to write something like

int pos = myFunc(str2);
String str3 = str2.substring(0,pos);

3 Comments

Thanks, Sanjay, but what if I don't want to return any new object in myFunc. I would like to modify the object with reference "str". Is that possbile?
@AlfredZhong I'm sorry , I dint get you :( whats wrong with retuning a value from a function? Another option is to declare a global variable pos, and change its value inside the function.
Thanks. There is nothing wrong. And I think it is very good. I am just curious if there is a way similar to C++.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.