Find the nth occurrence of substring in a string

Mark’s iterative approach would be the usual way, I think. Here’s an alternative with string-splitting, which can often be useful for finding-related processes: And here’s a quick (and somewhat dirty, in that you have to choose some chaff that can’t match the needle) one-liner:

Java substring: ‘string index out of range’

I”m guessing i’m getting this error because the string is trying to substring a Null value. But wouldn’t the “.length() > 0” part eliminate that issue? No, calling itemdescription.length() when itemdescription is null would not generate a StringIndexOutOfBoundsException, but rather a NullPointerException since you would essentially be trying to call a method on null. As … Read more

How does String substring work in Swift

All of the following examples use Swift 4 Strings got a pretty big overhaul in Swift 4. When you get some substring from a String now, you get a Substring type back rather than a String. Why is this? Strings are value types in Swift. That means if you use one String to make a new one, then … Read more

What is the difference between String.subString() and String.subSequence()

Using str.subSequence(begin, end) returns a CharSequence which is a read-only form of the string represented as a sequence of chars. For example: It’s read only in the sense that you can’t change the chars within the CharSequence without instantiating a new instance of a CharSequence. If you have to use str.subSequence(begin, end), you can cast the result to a String: and use all the normal String operators like subSequence … Read more

How do I check if a string contains a specific word?

You can use the strpos() function which is used to find the occurrence of one string inside another one: Note that the use of !== false is deliberate (neither != false nor === true will return the desired result); strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn’t found. Since 0 is a … Read more