Join list into one string - arrays

How to remove the first word of a string?
0.91% ABC DEF
0.922% ABC DEF GHI
OUTPUT: ABC DEF / ABC DEF GHI
I tried
let test = str.split(separator: " ")[1...]
print(test)
print(test.joined(separator: " "))
Which gives me:
["ABC", "DEF"]
JoinedSequence<ArraySlice<Substring>>(_base: ArraySlice(["ABC", "DEF"]), _separator: ContiguousArray([" "]))
How can I print the JoinedSequence as a string?

Try this:
let str = "0.91% ABC DEF"
var parts = str.components(separatedBy: " ").dropFirst()
print(parts.joined(separator: " "))
Which prints:
"ABC DEF\n"

Given a string
let text = "0.91% ABC DEF"
you can search for the ´index´ after the first space
if let index = text.range(of: " ")?.upperBound {
let result = text.substring(from: index)
print(result)
}

Related

Strings: How to combine first and last names in a long text string with other words?

Problem:
I have a given string = "Hello #User Name and hello again #Full Name and this works"
Desired output: = ["#User Name, #Full Name"]
Code I have in Swift:
let commentString = "Hello #User Name and hello again #Full Name and this works"
let words = commentString.components(separatedBy: " ")
let mentionQuery = "#"
for word in words.filter({ $0.hasPrefix(mentionQuery) }) {
print(word) = prints out each single name word "#User" and "#Full"
}
Trying this:
if words.filter({ $0.hasPrefix(mentionQuery) }).isNotEmpty {
print(words) ["Hello", "#User", "Name".. etc.]
}
I'm stuck on how to get an array of strings with the full name = ["#User Name", "#Full Name"]
Would you know how?
First of all, .filter means that check each value in the array which condition you given and if true then take value - which not fit here.
For the problem, it can divide into two task: Separate string into substring by " " ( which you have done); and combine 2 substring which starts with prefix "#"
Code will be like this
let commentString = "Hello #User Name and hello again #Full Name"
let words = commentString.components(separatedBy: " ")
let mentionQuery = "#"
var result : [String] = []
var i = 0
while i < words.count {
if words[i].hasPrefix(mentionQuery) {
result.append(words[i] + " " + words[i + 1])
i += 2
continue
}
i += 1
}
The result
print("result: ", result) // ["#User Name", "#Full Name"]
You can also use filter, like this below:
let str = "Hello #User Name and hello again #Full Name"
let res = str.components(separatedBy: " ").filter({$0.hasPrefix("#")})
print(res)
// ["#User", "#Full"]

Swift how to read through all indexes of array using for loop with index [i]

The Code I have so far only does for 1 index however I want it to read all existing indexes within the array. element array can carry many groups of numbers for example
Array ["2,2,5" , "5,2,1"] contains 2 indexes [0] and [1]
var element = Array[0]
let splitData = element.components(separatedBy: ",")
// split data will always contain 3 values.
var value1 = splitData[0]
var value2 = splitData[1]
var value3 = splitData[2]
print("value 1 is : " + value1 + " value 2 is : " + value2 + " value 3 is: " + value3)
the output of this code when Array ["2,2,5" , "5,2,1"] is :
value 1 is : 2 value 2 is : 2 value 3 is : 5
As the output suggests how can i iterate through all indexes of Array to display each of their 3 values.
I want the output to be :
value 1 is : 2 value 2 is : 2 value 3 is : 5
value 1 is : 5 value 2 is : 2 value 3 is : 1
I believe I need to use a for loop however I am unsure how to apply it to this. I am quite new to coding. Any help will be Appreciated
for i in 0..<array.count {
var element = array[i]
let splitData = element.components(separatedBy: ",")
// split data will always contain 3 values.
var value1 = splitData[0]
var value2 = splitData[1]
var value3 = splitData[2]
print("value 1 is : " + value1 + " value 2 is : " + value2 + " value 3 is: " + value3)
}
here are two solutions you can use, depending on what is the best result for you.
1) If your goal is to transform an array like ["3,4,5", "5,6", "1", "4,9,0"] into a flattened version ["3", "4", "5", "5", "6", "1", "4", "9", "0"] you can do it easily with the flatMap operator in the following way:
let myArray = ["3,4,5", "5,6", "1", "4,9,0"]
let flattenedArray = myArray.flatMap { $0.components(separatedBy: ",") }
Then you can iterate on it like every other array,
for (index, element) in myArray.enumerated() {
print("value \(index) is: \(element)")
}
2) If you just want to iterate over it and keep the levels you can use the following code.
let myArray = ["3,4,5", "5,6", "1", "4,9,0"]
for elementsSeparatedByCommas in myArray {
let elements = elementsSeparatedByCommas.components(separatedBy: ",")
print(elements.enumerated().map { "value \($0) is: \($1)" }.joined(separator: " "))
}
Hope that helps!

How to convert an array into a string with two different separators at two different places in ruby?

I want to convert an array in to a string with two different separators at two different places. meaning:
array = [1,2,3,4]
after converting: separator 1: (":") separator 2: ("and")
string = "1:2:3: and 4"
OR
string = "1:2 and 3:4"
How can I build dynamic and short code that lets me convert an array (of any length) into a string which allows me to insert more than one separator and at different positions.
My current solution is messy and hideous:
I have used #join with a single argument.
def oxford_comma(array)
if array.length == 1
result_at_1 = array.join
return result_at_1
elsif array.length == 2
result_at_2 = array.join(" and ")
return result_at_2
elsif array.length == 3
last = array.pop
result = array.join(", ")
last = ", and " + last
result = result + last
elsif array.length > 3
last = array.pop
result = array.join(", ")
last = ", and " + last
result = result + last
return result
end
end
Can someone please help me establish a better, shorter and more abstract method of doing this?
You can use Enumerable#slice_after.
array.slice_after(1).map { |e| e.join ":" }.join(" and ") #=> "1 and 2:3:4"
array.slice_after(2).map { |e| e.join ":" }.join(" and ") #=> "1:2 and 3:4"
array.slice_after(3).map { |e| e.join ":" }.join(" and ") #=> "1:2:3 and 4"
If you're using rails/activesupport, then it's built-in:
[1,2,3,4].to_sentence # => "1, 2, 3, and 4"
[1,2].to_sentence # => "1 and 2"
[1,2,3,4].to_sentence(last_word_connector: ' and also ') # => "1, 2, 3 and also 4"
If you don't, go copy the activesupport's implementation, for example :)
Note: this does not allow you to place your "and" in the middle of the sequence. Perfect for oxford commas, though.
pos = 2
[array[0...pos], array[pos..-1]].
map { |e| e.join ':' }.
join(' and ')
#⇒ "1:2 and 3:4"
Code
def convert(arr, special_separators, default_separator, anchors={ :start=>'', :end=>'' })
seps = (0..arr.size-2).map { |i| special_separators[i] || default_separator }
[anchors.fetch(:start, ""), *[arr.first, *seps.zip(arr.drop(1)).map(&:join)],
anchors.fetch(:end, "")].join
end
Examples
arr = [1,2,3,4,5,6,7,8]
default_separator = ':'
#1
special_separators = { 1=>" and ", 3=>" or " }
convert(arr, special_separators, default_separator)
#=> "1:2 and 3:4 or 5:6:7:8"
where
seps #=> [":", " and ", ":", " or ", ":", ":", ":"]
#2
special_separators = { 1=>" and ", 3=>") or (", 5=>" and " }
convert(arr, special_separators, default_separator, { start: "(", end: ")" })
#=> "(1:2 and 3:4) or (5:6 and 7:8)"
where
seps #=> [":", " and ", ":", ") or (", ":", " and ", ":"]

groovy transpose 2d array different sizes

With groovy I want to make a transpose on list of lists(with different sizes).
def mtrx = [
[1,2,3],
[4,5,6,7]
]
expected result:
[[1,4],[2,5],[3,6],[null,7]]
or
[[1,4],[2,5],[3,6],[7]]
Method .transpose() is working for equal sized is working fine, but for not equal - some elements are cut off.
My code is:
def max = 0
def map = [:]
def mapFinal = [:]
def row = 0
def mtrx = [
[1,2,3],
[4,5,6,7]
]
mtrx.each{it->
println it.size()
if(max < it.size()){
max = it.size()
}
}
def transposed = mtrx.each{it->
println it
it.eachWithIndex{it1, index->
println it1 + ' row ' + row + ' column ' +index
mapFinal[row+''+index] = it1
map[index+''+row] = it1
}
row++
}
println map
println mapFinal
Try
(0..<(mtrx*.size().max())).collect {
mtrx*.getAt(it)
}

How to remove array items from string?

I have this string: This is my example #foo and #bar
And this array: ['#foo','#bar']
And this is the string I would like to have: This is my example and
Thx!
Define your string and array:
s = "This is my example #foo and #bar"
a = ['#foo', '#bar']
Then:
answer_array = (s.split(" ") - a).join(" ")
Gives the answer:
=> "This is my example and"
The following preserves whitespace:
str = 'This is my example #foo and #bar'
arr = ['#foo','#bar']
r = Regexp.new arr.each_with_object('') { |s,str| str << s << '|' }[0..-2]
#=> /#foo|#bar/
str.gsub(r,'')
#=> "This is my example and "
Another example (column labels):
str = " Name Age Ht Wt"
arr = [' Age', ' Wt']
r = Regexp.new arr.each_with_object('') { |s,str| str << s << '|' }[0..-2]
#=> / Age| Wt/
str.gsub(r,'')
#=> " Name Ht"

Resources