Suppose you want to convert a String of length n to a character array of length n.
char [] chArray = someString.toCharArray();
What is the computation complexity?O(n) or O(1) ( n: length of someString)
I am under the impression that all it does is to allocate memory of size n*sizeof(char) and make a copy of that string to that location. So copying n cells of memory takes O(n) time. Is it ?
or it could be O(1), ( simple pointer relocation or as mentioned here)?
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.
The Java toCharArray() method is used to convert a sequence of characters stored in a string to an array of chars. In this tutorial, we covered how to use the toCharArray() method in Java. You now have the knowledge you need to convert strings to char arrays in Java using toCharArray().
The answer is linear time.
Think of it as copying single char and putting it into an array. It depends on number of elements so it's O(n).
It's linear time; it does the copy, and copies take linear time. (The constant factor might be quite low, but it's still linear overall.)
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