如何使字符串的特定字母大写,而不更改其他字母?
我的例子:
"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
我的系统使用UTF-8编码的字符,因此它需要支持UTF-8字符的大写字母,而不仅仅是ascii。
答案 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
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
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
答案 1 :(得分:6)
未优化的单线:)
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"
答案 2 :(得分:4)
如果您正在使用简单的ASCII字符串,这是另一个片段:
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"
这种方法的一个小优点是它可以被简单地修改为
`toupper(x, i, j) = x[1:i-1] * uppercase(x[i:j]) * x[j+1:end]`
将字符串中的 range 转换为大写,而不是单个字母。