# Is this the best way to convert a NUL terminated C-string into a Julia \`String\`?

**URL:** https://discourse.julialang.org/t/is-this-the-best-way-to-convert-a-nul-terminated-c-string-into-a-julia-string/55037
**Category:** General Usage
**Created:** [February 11, 2021, 12:11am UTC](https://discourse.julialang.org/t/is-this-the-best-way-to-convert-a-nul-terminated-c-string-into-a-julia-string/55037 "2021-02-11T00:11:57Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![BridgeBot](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bridgebot/32/21491_2.png) [@BridgeBot](https://discourse.julialang.org/u/BridgeBot)
#### Post date: [February 11, 2021, 12:11am UTC](https://discourse.julialang.org/t/is-this-the-best-way-to-convert-a-nul-terminated-c-string-into-a-julia-string/55037/1 "2021-02-11T00:11:57Z")

</div>

Is this the best way to convert a NUL terminated C-string into a Julia `String`?

```julia
julia> typeof(text)
Array{UInt8,1}

julia> unsafe_string(pointer(text))
"C14120-20P"

```

Note that the original poster on Slack cannot see your response here on Discourse. Consider _transcribing the appropriate answer back to Slack_, or pinging the poster here on Discourse so they can _follow this thread_.  
[(Original message :slack:)](https://julialang.slack.com/archives/C6A044SQH/p1613002293010100?thread_ts=1613002293.010100&cid=C6A044SQH) [(More Info)](https://github.com/JuliaCommunity/SlackBridge)

---

<div class="post-metadata">

### Author: ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)
#### Post date: [February 11, 2021, 2:25am UTC](https://discourse.julialang.org/t/is-this-the-best-way-to-convert-a-nul-terminated-c-string-into-a-julia-string/55037/2 "2021-02-11T02:25:19Z")

</div>

You have to be careful in general with this kind of code, because the pointer is not “rooted” — you need to make sure that `text` does not get garbage-collected into oblivion before `unsafe_string` is done with it. One option is to do:

```julia
GC.@preserve text s = unsafe_string(pointer(text))

```

Another option is to avoid “unsafe” pointer operations and do something like:

```julia
String(text[1:findfirst(==(0x00), text)-1])

```

What is the “best” way depends on what your criteria are, and in general will depend on the context. (For example, where does your `text` array come from? It might be possible to read directly into a string buffer without making a copy.)
