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.
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"
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.
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
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
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
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