Home > Software design >  How to convert string to array with no spaces
How to convert string to array with no spaces

Time:11-16

Related:

How to convert from string to array?

This is a follow-up question. How would I make a list of all the digits in this number (currently as a string)?

"123" -> [1,2,3]

There are no delimiters here so how should I go about doing this?

Note as of now I am using the latest version of Julia, v1.8.3 so parse doesn't seem to work in the other question's answers. Error when I use parse():

ERROR: LoadError: MethodError: no method matching parse(::SubString{String})
Closest candidates are:
  parse(::Type{T}, ::AbstractString) where T<:Complex at parse.jl:381
  parse(::Type{Sockets.IPAddr}, ::AbstractString) at ~/usr/share/julia/stdlib/v1.8/Sockets/src/IPAddr.jl:246
  parse(::Type{T}, ::AbstractChar; base) where T<:Integer at parse.jl:40
  ...
Stacktrace:
 [1] iterate
   @ ./generator.jl:47 [inlined]
 [2] _collect
   @ ./array.jl:807 [inlined]
 [3] collect_similar
   @ ./array.jl:716 [inlined]
 [4] map
   @ ./abstractarray.jl:2933 [inlined]
 [5] top-level scope
   @ ~/proc/self/fd/0:1
in expression starting at /proc/self/fd/0:1
exit status 1

CodePudding user response:

  1. Easy peasy like this:

    function str2vec(s::String)
        return map(x->parse(Int,x), split(s,""))
    end
    
    julia> str2vec("124")
    3-element Vector{Int64}:
     1
     2
     4
    
  2. Or by broadcasting:

    julia> parse.(Int, split("124",""))
    3-element Vector{Int64}:
     1
     2
     4
    
  3. By piping functions:

    julia> "124" |> x->split(x, "") |> x->parse.(Int, x)
    3-element Vector{Int64}:
     1
     2
     4
    
  4. Utilizing the eachsplit function, which is a lazy function and returns a generator object (introduced in Julia 1.8):

    julia> eachsplit("124", "") |> x->parse.(Int, x)
    3-element Vector{Int64}:
     1
     2
     4
    

CodePudding user response:

I guess the easiest way could be this:

const sentence = 'Sentence with words and numbers 12345';
let sentenceArray = sentence.replace(/\s/g, '').split('');
console.log(sentenceArray);

  • Related