Re: [julia-users] How to change the character at a specific position of a string?

1,807 views
Skip to first unread message

Stefan Karpinski

unread,
Dec 22, 2015, 4:44:42 PM12/22/15
to Julia Users
Strings are immutable. There is no API to do this. You can construct a new string object by doing s[1:1]*"b"*s[3:end].

On Tue, Dec 22, 2015 at 4:06 PM, Dongning Guo <dongni...@gmail.com> wrote:

Simple question: How to change the character at a specific position of a string?  Searched for a while in vain.  Thanks.


For example:

julia> s=^("a",4)

"aaaa"

How to change the second character to 'b', that is to change s to:

"abaa"





Erik Schnetter

unread,
Dec 22, 2015, 5:20:46 PM12/22/15
to julia...@googlegroups.com
You can use an array of characters instead of a string. This allows you to modify individual characters as necessary. Alternatively, an array of UInt8 make make sense (if you only need ASCII characters).

-erik

Tomas Lycken

unread,
Dec 23, 2015, 7:37:18 AM12/23/15
to julia-users

If/when you need the result, you can use join to get a string. For example:

julia> as = collect("aaaa")
4-element Array{Char,1}:
 'a'
 'a'
 'a'
 'a'

julia> as[2] = 'b'
'b'

julia> as
4-element Array{Char,1}:
 'a'
 'b'
 'a'
 'a'

julia> join(as)
"abaa"

// T

Reply all
Reply to author
Forward
0 new messages