Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a specific letter of a string uppercase in Julia?

How do I make a specific letter of a string uppercase, and not changing any of the other letters?

My example:

"this works" -> "this woRks" //Change made to letter 7
"this works" -> "this wOrks" //Change made to letter 6
"this works" -> "This works" //Change made to letter 1

My system uses characters with a UTF-8 encoding, so it needs to support uppercase for UTF-8 characters and not just ascii.

like image 799
Tech Labradoodle Avatar asked Jul 17 '18 13:07

Tech Labradoodle


3 Answers

Unoptimized one-liner :)

julia> s = "this is a lowercase string"
"this is a lowercase string"

julia> String([i == 4 ? uppercase(c) : c for (i, c) in enumerate(s)])
"thiS is a lowercase string"
like image 145
Oliver Evans Avatar answered Oct 21 '22 03:10

Oliver Evans


Here's another snippet if you're working with simple ASCII strings:

toupper(x, i) = x[1:i-1] * uppercase(x[i:i]) * x[i+1:end]

julia> toupper("this works", 1)
"This works"

julia> toupper("this works", 4)
"thiS works"

julia> toupper("this works", 7)
"this wOrks"

A slight advantage of this approach is that it can be trivially adapted as

`toupper(x, i, j) = x[1:i-1] * uppercase(x[i:j]) * x[j+1:end]`

to convert to uppercase a range within the string as opposed to a single letter.

like image 36
Tasos Papastylianou Avatar answered Oct 21 '22 05:10

Tasos Papastylianou


This is how can you do it with slicing a string:

In Julia 0.6

function uppercasen(s::AbstractString, i::Int)
    0 < i <= length(s) || error("index $i out of range")
    pos =  chr2ind(s, i)
    string(s[1:prevind(s, pos)], uppercase(s[pos]), s[nextind(s, pos):end])
end

for i in 1:3
    println(uppercasen("kół", i))
end

In Julia 0.7 (here I use SubString as it will be a bit faster than using String - similar thing can be done in Julia 0.6)

function uppercasen(s::AbstractString, i::Int)
    0 < i <= length(s) || error("index $i out of range")
    pos =  nextind(s, 0, i)
    string(SubString(s, 1, prevind(s, pos)), uppercase(s[pos]), SubString(s, nextind(s, pos)))
end

for i in 1:3
    println(uppercasen("kół", i))
end

However, the code below should work under both versions of Julia (unfortunately it is slower):

function uppercasen(s::AbstractString, i::Int)
    0 < i <= length(s) || error("index $i out of range")
    io = IOBuffer()
    for (j, c) in enumerate(s)
        write(io, i == j ? uppercase(c) : c)
    end
    String(take!(io))
end
like image 25
Bogumił Kamiński Avatar answered Oct 21 '22 05:10

Bogumił Kamiński