1

I want to get the first 4 characters of a string to compare with another string. However, when I do something like

String shortString;
shortString = longString.subString(0,3);

It takes along longString's backing array and makes it impossible to compare easily.

I've also tried converting longString into a character array and inserting each character but I always seem to end up with long string. The Android Development documents say to use the String constructor to remove the backing array but it doesn't seem to work for me either.

String shortString = new String(longString.subString(0,3));

Any suggestions would be appreciated!

3 Answers 3

2

First, it's string.substring() not .subString().

Second, what do you mean "impossible to compare easily"? You can compare strings with .equals() easily.

public static void main(String[] args) {
    String longString = "abcdefghijklmn";
    String shortString = longString.substring(0, 3);
    System.out.println(shortString.equals(longString));
}

this code prints false, as it should.

Update:

If you call .substring() so that it produces string of the same length as original string (e.g. "abc".substring(0,2)) than it will return reference to the same string. So, .equals() in this case will return true.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry about the typo. I was using == for comparison but .equals() seems to work all right. I should have thought of that off the bat. Thanks for the help!
0

How would you want to compare? There's built in method for simple comparison:

longString.subString(0, 3).compareTo(anotherString); 

Alternatively, since String is a CharSequence, something like:

for (int i=0; i<4; i++){
    if (anotherString.charAt(i) != shortString.charAt(i)) return false;
}

would work as well.

Finally, every String is constructed in backing Array, there's no way to deny it, and longString.subString(0,3) would always (except index out of bound) return a String with a 4-element Char Array.

1 Comment

Actually substring() returns a new String that has the same backing array.
0

In the event that you actually need to get rid of the backing array the following will work:

String newString = StringBuilder(oldString).toString();

This might be necessary, for example, if you are parsing strings and creating substrings and you might need to do this:

String newString = StringBuilder(oldString.substring(start,end).toString();

This creates a truly new string with a zero offset and independent backing array. Otherwise, you maintain the same backing array which, in rare cases might cause a problem for the heap because it can never be garbage collected.

Comments

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.