Tec*_*dle 3 string uppercase julia
如何创建字符串大写的特定字母,而不更改任何其他字母?
我的例子:
"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
Run Code Online (Sandbox Code Playgroud)
我的系统使用UTF-8编码的字符,因此它需要支持UTF-8字符的大写,而不仅仅是ascii.
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
Run Code Online (Sandbox Code Playgroud)
SubString它会比使用更快一些String- 类似的事情可以在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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
未经优化的单线:)
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"
Run Code Online (Sandbox Code Playgroud)
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]
Run Code Online (Sandbox Code Playgroud)
julia> toupper("this works", 1)
"This works"
julia> toupper("this works", 4)
"thiS works"
julia> toupper("this works", 7)
"this wOrks"
Run Code Online (Sandbox Code Playgroud)
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]`
Run Code Online (Sandbox Code Playgroud)
to convert to uppercase a range within the string as opposed to a single letter.