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.
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.
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.
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.
Now, use the toCharArray() method to convert string to char array. char[] ch = str. toCharArray();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With