Use of Separator while accessing arrays - arrays

I'm learning Swift through Youtube using online compilers on Windows and while learning to access arrays, I experienced that I had to use "," as separator in place of "\" inside the print function. But "\" was used in the video I was watching (she was using Xcode on Mac). What's the reason behind this? I've provided the code below.
import Foundation
let friends = ["Alisa", "Alice", "Joseph"]
print("friend 1: " ,(friends[1]))

In String Interpolation each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash \(var)
let friends = ["Alisa", "Alice", "Joseph"]
print("friend 1: \(friends[0])")
Or you can create a string with Format Specifiers
print(String(format:"friend 2: %#", friends[0]))
print statement accepts a list of Any objects. In the below line both objects are separated by comma
print("friend 1: " ,(friends[1]))//friend 1: Alice
print(1,2,3)//1 2 3

The technique is String Interpolation.
You construct a new string from string literals.
let name = "Bob"
//Returns: Hi Bob"
print("Hi \(name)")
Read more at: https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID292
A string literal is a predefined string value.
//This is a string literal.
let name = "Bob"
You can still use array values with String Interpolation.
let friends = ["Alisa", "Alice", "Joseph"]
let friend1 = friends[1]
print("friend 1: \(friend1)")
print("friend 1: \(friends[1])")
//These 2 print methods return same value.
//One is a constant, one is an array element.

Related

How create string array from single string in Kotlin

I have a string line from EditText, all words separated from each other by comma just like this:
"Some, string, words, bla-bla"
And I need to create array from this string, each element would be separate:
"Some", "string", "words", "bla-bla"
So, I saw how it was done on Java here but idk how convert it to kotlin, as I know Kotlin doesn't have split operator
This array I will save in preferences by putStringSet and use in another activity
Kotlin has a split function too. It will return a List<String>. If you you need an array in the end, call toTypedArray():
val strArray: Array<String> = "Some, string, words, bla-bla".split(", ").toTypedArray()

Empty array using scan functrion ruby

I'm just getting started in ruby and I have some trouble understanding the scan method:
my_string = "0000000001000100"
string_group = my_string.scan('/...../')
puts string_group
puts string_group.class
It displays that I've got an array but the array is empty. It can't come from my regex because I tested it and tried with another one:
'/[01]{5}/'
Why do I get an empty array?
Because regexes in Ruby are literal, not strings -- you have single quotes around your regex, so scan is searching for the literal string /...../ rather than matches to the regex /...../. Try this instead:
my_string = "0000000001000100"
string_group = my_string.scan(/...../)
Which gives this:
["00000", "00001", "00010"]

Javascript array manipulation / splice(), slice()

Javascript beginner.
I apply the split() method to the string, and next apply the splice() array method to the words array, removing two words at array "index 3", "really" and "cool" Since the splice () method returns any deleted words to display these in an alert dialog.
But "index" is unhappy with the code.
the output from script is:
JpowerfulaScript is really cool language
I want the output "javascript is perfect language"
enter image description here
Complete solution here
function wrangleArray() {
var sentence = "JavaScript is really cool language";
document.getElementById('div1').innerHTML = "<p>"+ sentence + "</p>";
var words = sentence.split(" ");
words.splice(2, 2, "powerful");
document.getElementById('div2').innerHTML = '<p>'+ words.join(" ") + '</p>';
}
As far as I can see from your code, you have this line:
var words = sentence.split('');
Your mistake here as I see it is, you are not splitting by spaces (' ') but rather by empty strings.
As can be seen from this fiddle splitting by an empty string (the '' entry in your code), means splitting by every character (since after every character you technically do have an empty string).

Swift, handle Arrays and Datatypes (Split String from String) [duplicate]

This question already has answers here:
How does String.Index work in Swift
(4 answers)
Closed 6 years ago.
I just started with Swift a few days ago and I am struggling with all the different Datatypes...
Lets say we do this:
var myarray = ["justin", "steve", "peter"]
var newString = myarray[2]
so why I cant now print just the "p" from "peter"?
print(newString[0])
---> gives me an error:
"'subscript' is unavailable: cannot subscript String with an Int"
in this topic:
[Get nth character of a string in Swift programming language
it says:
"Note that you can't ever use an index (or range) created from one string to another string"
But I cant imagine, that there isn't way to handle it...
Because When I do this:
var myarray = ["justin", "steve", "p.e.t.e.r"]
var newString = myarray[2]
let a : [String] = newString.componentsSeparatedByString(".")
print(a[2])
then it works. It prints (in this case) "t".
So how I can split it "SeparatedByString" 'Nothing'?
Im sure to solve this will help me also at many other problems.
I hope I postet the question in the way it should be done.
Thank you for any solution or tips :)
The instance method componentsSeparatedByString applied to a String instance yields an array of String instances, namely [String]. The elements of an array can be indexed in the classic Java/C++ fashion (let thirdElement = array[2]).
If you'd like to split your String instance ("peter") into an array of single character String instances, you can make use of the CharacterView property of a String instance, and thereafter map each single Character in the CharacterView back to a single-character String instance
let str = "peter"
let strArray = str.characters.map(String.init(_:)) // ["p", "e", "t", "e", "r"]
let thirdElement = strArray[2] // t
This is quite roundabout way though (String -> CharacterView -> [String] -> String), and you're most likely better off simply looking at the excellent answer (covering direct String indexing) in the dupe thread dug up by #Hamish:
How does String.Index work in Swift 3
The possible corner case where the above could be applicable, as pointed out by Hamish below, is if you very frequently need access to characters in the String at specific indices, and like to make use of the O(1) random access available to arrays (more so applicable if you are working with immutable String:s, such that the corresponding String array only needs to be generated once for each immutable String instance).

Using variables with %w or %W - Ruby

I have a similar issue as this post:
How to use variable inside %w{}
but my issue is a bit different. I want to take a string variable and convert it to an array using %w or %W.
text = gets.chomp # get user text string
#e.g I enter "first in first out"
words = %w[#{text}] # convert text into array of strings
puts words.length
puts words
Console output
1
first in first out
Keeps the text as a block of string and doesn't split it into an array words ["first","in", "first", "out"]
words = text.split (" ") # This works fine
words = %w[#{gets.chomp}] # This doesn't work either
words = %w['#{gets.chomp}'] # This doesn't work either
words = %W["#{gets.chomp}"] # This doesn't work either
words = %w("#{gets.chomp}") # This doesn't work either
%w is not intended to do any splitting, it's a way of expressing that the following string in the source should be split. In essence it's just a short-hand notation.
In the case of %W the #{...} chunks are treated as a single token, any spaces contained within are considered an integral part.
The correct thing to do is this:
words = text.trim.split(/\s+/)
Doing things like %W[#{...}] is just as pointless as "#{...}". If you need something cast as a string, call .to_s. If you need something split call split.

Resources