Can I find specific characters in a string in Julia?

Viewed 601

So I started using Julia, and I wonder if you can find a character in a string. For example:

x = "hello."

looks for a . (if it is there)

removes the .

x = "hello"

my program based on the answers (works now!):

# hello.jl
# --- Greeting ---
println("Hello!")
println("How are you?")
# --- Input ---
x = readline()
# --- Put the characters in the ' ' for use later ---
removechar = ['.', '!', '*', '(', ')',' ']
# --- Fixing ---
fixedX = replace(lowercase(x), removechar => "")
# --- Print Answer ---
println("I'm ", fixedX, " too!")
2 Answers

You can use replace to replace characters in a string (even if those characters are not in the string):

julia> replace("hello.", "." => "")
"hello"

julia> replace("world", "." => "")
"world"

If you just want a boolean indicating whether a sub-string exists in a string, you can use contains or occursin:

julia> contains("the quick brown fox", "fox")
true

julia> occursin("fox", "the quick brown fox")
true

contains and occursin are basically the same, except the argument order is reversed. You can remember the argument order by reading the function name in between the two arguments, like this:

  • contains(x, y): "x contains y"

  • occursin(x, y): "x occurs in y"

You can replace several characters at once (I understand this is what you want) with the following replace syntax:

julia> replace("hello.", ['.', 'o','e'] => "")
"hll"

enter image description here

Related