How to make a switch case in Swift to continue to the next case condition? [duplicate] - switch-statement

This question already has answers here:
swift case falling through
(5 answers)
Closed 8 years ago.
In Swift, once a switch condition is reached it does implicitly "break" and get out of the switch case. In other terms it does not continues to the next condition one. How to achieve the regular behaviour as in C, C++, java, javascript etc… ?

Taken from the Apple Swift documentation:
If you really need C-style fallthrough behavior, you can opt in to this behavior on a case-by-case basis with the fallthrough keyword. The example below uses fallthrough to create a textual description of a number:
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and also"
fallthrough // explicitly tells to continue to the default case
default:
description += " an integer."
}
println(description)
// prints "The number 5 is a prime number, and also an integer."

Related

Was trying to get it to return the index value of multiple instances of the same character rather than just the first, can't figure out what happened

So, was just trying to see if I could figure out a way to get it to print the index value of not only the first "o" character, but also the second, so the output would clearly have to be 4, 8.
string = "Python for Beginners"
x = "o"
for x in string:
print (string.index (x))
My reasoning being that for every character equal to "o" in the string, it would give me its specific index count. Instead, it gave me this as an output
0
1
2
3
4
5
6
7
4
9
6
11
12
13
14
5
5
12
9
19
So other than not doing what I thought it would, I've spent most of the past hour trying to figure out the logic that got me that output but alas, being a noob, I couldn't figure it out for the life of me.
I'd be interested in a solution on how to get it to count multiple instances of the same character, but even more interested in understanding exactly what happened to give me that output. Just can't figure it out.
Cheers all
OK so with a bit of diggin arouund i found of the re.finditer command which first requires us to import re (regular expression). I actually have no idea what that means but figured out enough to use it. Credit to this thread Finding multiple occurrences of a string within a string in Python
Then just played around a bit but finally got it down to this
string = "Python for Beginners"
import re
search = input ("What are you looking for? ")
msg = f" '{search}' found at index: "
for x in re.finditer (search , string):
print (msg, x.start())
if string.find (search) == -1:
print ("Error: sequence not present in string. Note: search is case sensitive")
This is all just for the purposes of educating myself practically a little bit as I go through the learning. Cheers all. Still open to suggestions for "better ways" of achieving the same output.

How do I get a substring of a string in Julia?

Is there a way in Julia that gets from one particular character to another? For example, I want to get the variable s="Hello, world" of 3 to 9 characters.
# output = 'llo, wo'
The other solution is working for ASCII only strings. However, Julia uses byte indexing not character indexing in getindex syntax, as I have discussed on my blog some time ago. If you want to use character indexing (which I assume you do from the wording of your question) here you have a solution using macros.
In general (without using the solution linked above) the functions to use are: chop, first, last, or for index manipulation prevind, nextind, and length.
So e.g. to get characters from 3 to 9 a safe syntaxes are e.g. (just showing several combinations)
julia> str = "😄 Hello! 👋"
"😄 Hello! 👋"
julia> last(first(str, 9), 7)
"Hello! "
julia> chop(str, head=2, tail=length(str)-9)
"Hello! "
julia> chop(first(str, 9), head=2, tail=0)
"Hello! "
julia> str[(:)(nextind.(str, 0, (3, 9))...)]
"Hello! "
Note though that the following is incorrect:
julia> str[3:9]
ERROR: StringIndexError: invalid index [3], valid nearby indices [1]=>'😄', [5]=>' '
There is an open issue to make chop more flexible which would simplify your specific indexing case.
You can use the following method:
s="Hello, world"
s[3:9]
# output: llo, wo
s[3:end]
# output: llo, world

Why does drop() method in Scala allow negative value and does not throw error?

I am trying to get my hands dirty with Scala where is I am playing with scala.collection.immutable.StringOps on the terminal. In the String method drop(), I tried executing this code
"stackoverflow".drop(-12)
and the output I received was
stackoverflow
The -12 was a typo but this result is unexpected as it should truncate 12 characters from last or be an error or exception. Because when we pass an integer into the drop(), it eliminates the first characters from the string equivalent to the number of arguments. Why is this behavior kept with this method in Scala? Can this become useful in some scenarios? What is the reason for this behavior?
Scala has many other different behaviors that other languages don't support such as
true > false is true and true < false is false.
The documentation says "If n is negative, don't drop any elements". I'm guessing the reason is that in some cases it lets you skip doing some math. For instance, let's say you want to drop from the start of two strings so that they are equal length. You could do:
def makeSameLength(s1: String, s2: String): (String, String) = {
(s1.drop(s1.size-s2.size), s2.drop(s2.size-s1.size))
}
Cases like this where you have to drop some variable number of elements from a sequence come up a lot, and usually if the math works out to a negative number, that means you just don't want to drop anything at all. So this saves you from having to add in some conditional logic, or include a max(x, 0) or similar.
I do agree it's a bit surprising, but can see why it might be useful.

Make first letter of words uppercase in a string

I have a large array of strings such as this one:
"INTEGRATED ENGINEERING 5 Year (BSC with a Year in Industry)"
I want to capitalise the first letter of the words and make the rest of the words lowercase. So INTEGRATED would become Integrated.
A second spanner in the works - I want an exception to a few words such as and, in, a, with.
So the above example would become:
"Integrated Engineering 5 Year (Bsc with a Year in Industry)"
How would I do this in Go? I can code the loop/arrays to manage the change but the actual string conversion is what I struggle with.
There is a function in the built-in strings package called Title.
s := "INTEGRATED ENGINEERING 5 Year (BSC with a Year in Industry)"
fmt.Println(strings.Title(strings.ToLower(s)))
https://go.dev/play/p/THsIzD3ZCF9
You can use regular expressions for this task. A \w+ regexp will match all the words, then by using Regexp.ReplaceAllStringFunc you can replace the words with intended content, skipping stop words. In your case, strings.ToLower and strings.Title will be also helpful.
Example:
str := "INTEGRATED ENGINEERING 5 Year (BSC with a Year in Industry)"
// Function replacing words (assuming lower case input)
replace := func(word string) string {
switch word {
case "with", "in", "a":
return word
}
return strings.Title(word)
}
r := regexp.MustCompile(`\w+`)
str = r.ReplaceAllStringFunc(strings.ToLower(str), replace)
fmt.Println(str)
// Output:
// Integrated Engineering 5 Year (Bsc with a Year in Industry)
https://play.golang.org/p/uMag7buHG8
You can easily adapt this to your array of strings.
The below is an alternate to the accepted answer, which is now deprecated:
package main
import (
"fmt"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
func main() {
msg := "INTEGRATED ENGINEERING 5 Year (BSC with a Year in Industry)"
fmt.Println(cases.Title(language.English, cases.Compact).String(msg))
}
In Go 1.18 strings.Title() is deprecated.
Here you can read the following to know what to use now
you should use cases.Title instead.
Well you didn't specify the language you're using, so I'll give you a general answer. You have an array with a bunch of strings in it. First I'd make the entire string lower case, then just go through each character in the string (capitalize the first one, rest stay lower case). At this point you need to look for the space, this will help you divide up the words in each string. The first character after finding a space is obviously a different word and should be capitalized. You can verify the next word isn't and in with Or a as well.
I'm not at a computer so I can't give to a specific example, but I hope this gets to in the right direction at least

Breaking the each loop in Groovy [duplicate]

This question already has answers here:
Can you break from a Groovy "each" closure?
(8 answers)
Closed 10 years ago.
How will I break the loop if a particular condition is satisfied?
My input file has around n number of lines. If the required information is got at some mth line I need to break the loop instead of reading the remaining lines.
new File("test.txt").readLines().reverseEach{line ->
println line
if(line.contains("Data"))
break;
}
You could use find to do this. Find ends the loop the first time the closure returns true and returns the last found element.
This
(1..20).find{
println it
it == 5
}
Would be the following in the groovy console.
1
2
3
4
5
Result: 5
You can't just break from closure. You can either throw an exception and exit from it, or do not use closures at all. Read all lines in array/list and iterate through it.

Resources