Given that:
julia> SubString <: String
false
How would you write a function that accepts both substrings and strings?
julia> function myfunction(ss::String)
@show ss, typeof(ss)
end
myfunction (generic function with 1 method)
julia> myfunction("Hello World")
(ss, typeof(ss)) = ("Hello World", String)
("Hello World", String)
julia> s = split("Hello World")
2-element Array{SubString{String},1}:
"Hello"
"World"
julia> foreach(x -> myfunction(x), s)
ERROR: MethodError: no method matching myfunction(::SubString{String})
Closest candidates are:
myfunction(::String) at REPL[11]:2
a substring is a subsequence of a string in which the characters must be drawn from contiguous positions in the string. For example the string CATCGA, the subsequence ATCG is a substring but the subsequence CTCA is not.
String substring(begIndex, endIndex): This method has two variants and returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1 if the second argument is given.
Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of substrings.
Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.
I think there are two ways you can do this:
Use AbstractString
rather than String
in the function definition;
Define the function twice, once for String
and once for SubString
, which will generate myfunction (generic function with 2 methods)
.
The point is that SubString
is a subtype of AbstractString
, not String
. You can see this by entering supertype(SubString)
.
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