Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the run time of String.toCharArray()?

What's the run time of String.toCharArray() in java? The source code is

 public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
    char result[] = new char[value.length];
    System.arraycopy(value, 0, result, 0, value.length);
    return result;
}

Does System.arrayCopy? have run time of O(n)? The source code doesn't really say much about how it's implemented. Does it go through every element and copies it? Thanks.

like image 695
cinnamon toast Avatar asked Dec 27 '12 23:12

cinnamon toast


People also ask

What is the time complexity of toCharArray?

Next let's talk about complexity. In toCharArray(), it takes O(n) time to return the result, where n is the length of the string. It also takes O(n) space as it creates a defensive copy of the original string. In charAt(), it takes O(1) time to return the result as it's a random access.

What does toCharArray () do in Java?

The java string toCharArray() method converts the given string into a sequence of characters. The returned array length is equal to the length of the string. Syntax : public char[] toCharArray() Return : It returns a newly allocated character array.

What is toCharArray in C#?

In C#, ToCharArray() is a string method. This method is used to copy the characters from a specified string in the current instance to a Unicode character array or the characters of a specified substring in the current instance to a Unicode character array.

How do you make string toCharArray?

Now, use the toCharArray() method to convert string to char array. char[] ch = str. toCharArray();


1 Answers

System.arraycopy() is typically an intrinsic and is very fast. That said, it still has to look at (and copy) every element of the array, so its asymptotic complexity is linear in the length of the array, i.e. O(n).

Thus the complexity of toCharArray() is O(n), where n is the length of the string.

like image 132
NPE Avatar answered Oct 29 '22 14:10

NPE