Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with both strings and substrings

Tags:

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
like image 443
daycaster Avatar asked Jul 01 '18 12:07

daycaster


People also ask

What is difference between string and substring?

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.

Can you explain the working of substrings in string?

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.

How many substrings a string can have?

Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of substrings.

How would you read the string and split into 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.


1 Answers

I think there are two ways you can do this:

  1. Use AbstractString rather than String in the function definition;

  2. 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).

like image 109
Mark Birtwistle Avatar answered Sep 28 '22 17:09

Mark Birtwistle