How do I check if a String includes a specific Character? - string

How do I check if a String includes a specific Character?
For example:
if !emailString.hasCharacter("#") {
println("Email must contain at sign.")
}

You can use the free-standing find function, like this:
let s = "hello"
if (find(s, "x") != nil) {
println("Found X")
}
if (find(s, "l") != nil) {
println("Found L")
}

Here you go:
if emailString.rangeOfString("#") != nil{
println("# exists")
}

You can use this
if emailString.rangeOfString("#") == nil {
println("Email must contain at sign.")
}

Related

How to Return Nil String in Go?

I have a function which returns a string under certain circumstances, namely when the program runs in Linux or MacOS, otherwise the return value should be nil in order to omit some OS-specific checks further in code.
func test() (response string) {
if runtime.GOOS != "linux" {
return nil
} else {
/* blablabla*/
}
}
however when I try to compile this code I get an error:
test.go:10:3: cannot use nil as type string in return argument.
If I return just an empty string like return "", I cannot compare this return value with nil further in code.
So the question is how to return a correct nil string value?
If you can't use "", return a pointer of type *string; or–since this is Go–you may declare multiple return values, such as: (response string, ok bool).
Using *string: return nil pointer when you don't have a "useful" string to return. When you do, assign it to a local variable, and return its address.
func test() (response *string) {
if runtime.GOOS != "linux" {
return nil
} else {
ret := "useful"
return &ret
}
}
Using multiple return values: when you have a useful string to return, return it with ok = true, e.g.:
return "useful", true
Otherwise:
return "", false
This is how it would look like:
func test() (response string, ok bool) {
if runtime.GOOS != "linux" {
return "", false
} else {
return "useful", true
}
}
At the caller, first check the ok return value. If that's true, you may use the string value. Otherwise, consider it useless.
Also see related questions:
How do I represent an Optional String in Go?
Alternatives for obtaining and returning a pointer to string: How do I do a literal *int64 in Go?
Go has built-in support for multiple return values:
This feature is used often in idiomatic Go, for example to return both result and error values from a function.
In your case it could be like this:
func test() (response string, err error) {
if runtime.GOOS != "linux" {
return "", nil
} else {
/* blablabla*/
}
}
And then:
response, err := test()
if err != nil {
// Error handling code
return;
}
// Normal code
If you want to ignore the error, simply use _:
response, _ := test()
// Normal code
Go allows multiple return types. So use this to your advantage and return an error or any other type. Check this out for more info: http://golangtutorials.blogspot.com/2011/06/return-values-from-go-functions.html?m=1

Scanner() not working with if - else statement

My intention is to let the user decide which method to use by cheking its input.
I have the following code:
try {
String test = scan.next();
if(test == "y") {
//do stuff
}
else if (test == "n") {
//do stuff
}
} catch (Exception e) {
System.out.println("false");
}
I tried to analyze with the debugger. It is not jumping in the if-statement.
can you help me out here?
You need to use equals to compare strings
if(test == "y")
becomes
if (test.equals("y"))
Same for "n" obviously.
== test for reference equality, but you're looking for value equality, that's why you should use equals, and not ==.

Check multiple rangeOfString (Swift)

How do I perform multiple rangeOfString's but only if the value being checked has a value?
E.g. below
var string1 = "hello"
var string2 = "world"
var checker1 = "he"
var checker2 = ""
if string1.lowercaseString.rangeOfString(checker1) != nil {
println("exists1")
}
//SHOULD not perform below as the value below as "checker2" is empty.
if string2.lowercaseString.rangeOfString(checker2) != nil {
println("exists2")
}
You could just add a check if the string is non-empty:
if checker2 != "" && string2.lowercaseString.rangeOfString(checker2) != nil {
println("exists2")
}
But that is actually not necessary because rangeOfString() returns nil if called
with an empty argument. And if you rewrite the test as
if string2.rangeOfString(checker2, options: .CaseInsensitiveSearch) != nil {
println("exists2")
}
then there is even no overhead for the lowercaseString conversion in the empty
string case.

How to convert a 'string pointer' to a string in Golang?

Is it possible to get the string value from a pointer to a string?
I am using the goopt package to handle flag parsing and the package returns *string only. I want to use these values to call a function in a map.
Example
var strPointer = new(string)
*strPointer = "string"
functions := map[string]func() {
"string": func(){
fmt.Println("works")
},
}
//Do something to get the string value
functions[strPointerValue]()
returns
./prog.go:17:14: cannot use strPointer (type *string)
as type string in map index
Dereference the pointer:
strPointerValue := *strPointer
A simple function that first checks if the string pointer is nil would prevent runtime errors:
func DerefString(s *string) string {
if s != nil {
return *s
}
return ""
}
Generic https://stackoverflow.com/a/62790458/1079543 :
func SafeDeref[T any](p *T) T {
if p == nil {
var v T
return v
}
return *p
}

Swift: String contains String (Without using NSString)?

I have the same problem like in this question:
How do I check if a string contains another string in Swift?
But now a few months later I wonder if it can be done without using NSString?
I nice and simple contains-method would be fine.
I searched the web and the documentation but I found nothing!
Same way, just with Swift syntax:
let string = "This is a test. This is only a test"
if string.rangeOfString("only") != nil {
println("yes")
}
For Swift 3.0
if str.range(of: "abc") != nil{
print("Got the string")
}
String actually provides a "contains" function through StringProtocol.
No extension whatsoever needed:
let str = "asdf"
print(str.contains("sd") ? "yep" : "nope")
https://developer.apple.com/reference/swift/string
https://developer.apple.com/documentation/swift/stringprotocol
If you want to check if your string matches a specific pattern, I can recommend the NSHipster article about NSRegularExpressions: http://nshipster.com/nsregularexpression/
I wrote an extension on String for SWIFT 3.0 so that i could simply call absoluteString.contains(string: "/kredit/")
extension String {
public func contains(string: String)-> Bool {
return self.rangeOfString(string) != nil
}
}
just to demonstrate the use of options.
var string = "This is a test. This is only a test. Not an Exam"
if string.range(of:"ex") != nil {
print("yes")
}
if string.range(of:"ex", options: String.CompareOptions.caseInsensitive) != nil {
print("yes")
}

Resources