如何在Julia中创建字符串大写的特定字母?

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.

Bog*_*ski 6

这是你怎么做切片字符串:

在朱莉娅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
Run Code Online (Sandbox Code Playgroud)

在朱莉娅0.7(这里我使用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)

但是,下面的代码应该在两个版本的Julia下工作(不幸的是它更慢):

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)


Oli*_*ans 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"
Run Code Online (Sandbox Code Playgroud)


Tas*_*nou 5

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.

  • 不幸的是,这仅适用于 ASCII,而不适用于一般 UTF-8。查看:`toupper("Kół", 2)`。这就是为什么在我的回答中你需要使用 `nextind` 和 `prevind`。 (2认同)