Type Casting string to array

What is the time complexity of type casting string to array and vice versa. is it O(n) or O(1) ? and why ?

You can't cast a String to an Array. They are different types, with different memory layouts.

You can initialize a String from an Array, e.g.:

let array: [UInt8] = [72, 101, 108, 108, 111]
let string = String(validating: array, as: UTF8.self)! //  "Hello"

and you can initialize an Array from a String or one of its views:

let arrayOfCharacters = Array(string) // Array<Character>
let arrayOfUTF8 = Array(string.utf8)  // Array<UInt8>

both of these are O(n) operations, because they have to actually copy the data (and validate/transform it, in some cases).

If you want to do string-processing-type operations on buffers without copying the data, you will likely want to follow along with @Michael_Ilseman and @glessard's proposal for string processing on contiguous storage.

Another option which may or may not be viable for you today, depending on what you're doing, is to operate on the string's .utf8 view directly, instead of on an Array. It is a collection of bytes, and you can do many of the things that you would do with an Array with that view directly. If you can provide some more context about what you're trying to do, we can offer some suggestions.

7 Likes

I think you could get to the underlying bytes in O(1) if that's what you want doing. E.g. if the string in question is ascii then your bytes would be characters, otherwise it's probably UTF8 and the correspondence would be more complex.

@scanon So what made me ask this question is because of a problem I was solving on hackerRank, My solution exceeded the time limit of some of the tests. One part of the code I was taking an Int so instead of working with it I changed it like that Array(String(10)) then after finishing I do the opposite. After searching I found a way to work with the Int directly and it worked and passed all the tests after removing Array(String(10)) from code. This made me wonder what is the time complexity of this piece of code Array(String(10)) :thinking: that made my code takes so long