How to check whether a string contains a substring in Kotlin? - string

Example:
String1 = "AbBaCca";
String2 = "bac";
I want to perform a check that String1 contains String2 or not.

Kotlin has stdlib package to perform certain extension function operation over the string, you can check this method it will check the substring in a string, you can ignore the case by passing true/false value. Refer this link
"AbBaCca".contains("bac", ignoreCase = true)

The most idiomatic way to check this is to use the in operator:
String2 in String1
This is equivalent to calling contains(), but shorter and more readable.

You can do it by using the "in" - operator, e.g.
val url : String = "http://www.google.de"
val check : Boolean = "http" in url
check has the value true then. :)

See the contains method in the documentation.
String1.contains(String2);

Kotlin has a few different contains function on Strings, see here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/contains.html.
If you want it to be true that string2 is contained in string1 (ie you want to ignore case), they even have a convenient boolean argument for you, so you won't need to convert to lowercase first.

For anyone out there like me who wanted to do this for a nullable String, that is, String?, here is my solution:
operator fun String?.contains(substring:String): Boolean {
return if (this is String) {
// Need to convert to CharSequence, otherwise keeps calling my
// contains in an endless loop.
val charSequence: CharSequence = this
charSequence.contains(substring)
} else {
false
}
}
// Uses Kotlin convention of converting 'in' to operator 'contains'
if (shortString in nullableLongString) {
// TODO: Your stuff goes here!
}

Related

Use String isEmpty to check for empty string

Swift Programming Language mentions using isEmpty to check for empty string. Are there cases where checking string against "" not yield the same result as using isEmpty?
In other words:
if str.isEmpty {
XCTAssert(str == "", "This should be true as well")
}
From the documentation:
Find out whether a String value is empty by checking its Boolean isEmpty property:
if emptyString.isEmpty {
print("Nothing to see here")
}
The empty string is the only empty string, so there should be no cases where string.isEmpty() does not return the same value as string == "". They may do so in different amounts of time and memory, of course. Whether they use different amounts of time and memory is an implementation detail not described, but isEmpty is the preferred way to check in Swift (as documented).

How to extract substring in Groovy?

I have a Groovy method that currently works but is real ugly/hacky looking:
def parseId(String str) {
System.out.println("str: " + str)
int index = href.indexOf("repositoryId")
System.out.println("index: " + index)
int repoIndex = index + 13
System.out.println("repoIndex" + repoIndex)
String repoId = href.substring(repoIndex)
System.out.println("repoId is: " + repoId)
}
When this runs, you might get output like:
str: wsodk3oke30d30kdl4kof94j93jr94f3kd03k043k?planKey=si23j383&repositoryId=31850514
index: 59
repoIndex: 72
repoId is: 31850514
As you can see, I'm simply interested in obtaining the repositoryId value (everything after the = operator) out of the String. Is there a more efficient/Groovier way of doing this or this the only way?
There are a lot of ways to achieve what you want. I'll suggest a simple one using split:
sub = { it.split("repositoryId=")[1] }
str='wsodk3oke30d30kdl4kof94j93jr94f3kd03k043k?planKey=si23j383&repositoryId=31850514'
assert sub(str) == '31850514'
Using a regular expression you could do
def repositoryId = (str =~ "repositoryId=(.*)")[0][1]
The =~ is a regex matcher
or a shortcut regexp - if you are looking only for single match:
String repoId = str.replaceFirst( /.*&repositoryId=(\w+).*/, '$1' )
All the answers here contains regular expressions, however there are a bunch of string methods in Groovy.
String Function
Sample
Description
contains
myStringVar.contains(substring)
Returns true if and only if this string contains the specified sequence of char values
equals
myStringVar.equals(substring)
This is similar to the above but has to be an exact match for the check to return a true value
endsWith
myStringVar.endsWith(suffix)
This method checks the new value contains an ending string
startsWith
myStringVar.startsWith(prefix)
This method checks the new value contains an starting string
equalsIgnoreCase
myStringVar.equalsIgnoreCase(substring)
The same as equals but without case sensitivity
isEmpty
myStringVar.isEmpty()
Checks if myStringVar is populated or not.
matches
myStringVar.matches(substring)
This is the same as equals with the slight difference being that matches takes a regular string as a parameter unlike equals which takes another String object
replace
myStringVar.replace(old,new)
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar
replaceAll
myStringVar.replaceAll(old_regex,new)
Replaces each substring of this string that matches the given regular expression with the given replacement
split
myStringVar.split(regex)
Splits this string around matches of the given regular expression
Source

Best way to compare multiple string in java

Suppose I have a string "That question is on the minds of every one.".
I want to compare each word in string with a set of word I.e. (to , is ,on , of) and if those word occurs I want to append some string on the existing string.
Eg.
to = append "Hi";
Is = append "Hello";
And so on.
To be more specific I have used StringTokenizer to get the each word and compared thru if else statement. However we can use Switch also but it is available in Jdk 1.
7.
I don't know if this is what you mean, but:
You could use String.split() to separate the words from your string like
String[] words = myString.split(" ");
and then, for each word, compare it with the given set
for(String s : words)
{
switch(s)
{
case("to"):
[...]
}
}
Or you could just use the String.contains() method without even splitting your string, but I don't know if that's what you wanted.
Use a HashMap<String,String> variable to store your set of words and the replacement words you want. Then split your string with split(), loop through the resulting String[] and for each String in the String[], check whether the HashMap containsKey() that String. Build your output/resulting String in the loop - if the word is contained in the HashMap, replace it with the value of the corresponding key in the HashMap, otherwise use the String you are currently on from the String[].

How to manipulate Strings in Scala while using the Play framework?

I am using the play framework 2.2.1 and I have a question concerning the manipulation of Strings within view templates. Unfortunately I am not very familiar with the Scala programming language nor its APIs. The strings are contained in a List which is passed from the controller to the view and then I use a loop to process each string before they are added to the html. I would like to know how to do the following: trim, toLowerCase and remove spaces. As an example, if I have "My string ", I would like to produce "mystring". More specifically I would actually like to produce "myString", however I'm sure I can figure that out if someone points me in the right direction. Thanks.
UPDATE:
Fiaz provided a great solution, building on his answer and just for interest sake I came up with the following solution using recursion. This example is of course making many assumptions about the input provided.
#formatName(name: String) = #{
def inner(list: List[String], first: Boolean): String = {
if (!list.tail.isEmpty && first) list.head + inner(list.tail, false)
else if (!list.tail.isEmpty && !first) list.head.capitalize + inner(list.tail, false)
else if (list.tail.isEmpty && !first) list.head.capitalize
else list.head
}
if (!name.trim.isEmpty) inner(name.split(' ').map(_.toLowerCase).toList, true)
else ""
}
If you want to know how to do just the trimming, lower-casing and joining without spaces, try this perhaps?
// Given that s is your string
s.split(" ").map(_.toLowerCase).mkString
That splits a string into an array strings, splitting is done on one or more spaces so that gives you trimmed strings. You then map each element in the array with the function (x => x.toLowerCase) (for which the shorthand is (_.toLowerCase)) and then join the Array back into a single string using the mkString method that collections have.
So let's say you want to capitalize the first letter of the each of the space-split bits:
Scala provides a capitalize method on Strings, so you could use that:
s.split(" ").map(_.toLowerCase.capitalize).mkString
See http://www.scala-lang.org/api/current/scala/collection/immutable/StringOps.html
One suggestion as to how you can get the exact output (your example 'myString') you describe:
(s.split(" ").toList match {
case fst::rest => fst.toLowerCase :: rest.map(_.toLowerCase.capitalize)
case Nil => Nil }
).mkString
There is example of using the string manipulation below:
#stringFormat(value: String) = #{
value.replace("'", "\\'")
}
#optionStringFormat(description: Option[String]) = #{
if (description.isDefined) {
description.get.replace("'", "\\'").replace("\n", "").replace("\r", "")
} else {
""
}
}
#for(photo <- photos) {
<div id="photo" class="random" onclick="fadeInPhoto(#photo.id, '#photo.filename', '#stringFormat(photo.title)', '#optionStringFormat(photo.description)', '#byTags');">
This example obtained from https://github.com/joakim-ribier/play2-scala-gallery

Remove Characters from the end of a String Scala

What is the simplest method to remove the last character from the end of a String in Scala?
I find Rubys String class has some very useful methods like chop. I would have used "oddoneoutz".headOption in Scala, but it is depreciated. I don't want to get into the overly complex:
string.slice(0, string.length - 1)
Please someone tell me there is a nice simple method like chop for something this common.
How about using dropRight, which works in 2.8:-
"abc!".dropRight(1)
Which produces "abc"
string.init // padding for the minimum 15 characters
val str = "Hello world!"
str take (str.length - 1) mkString
If you want the most efficient solution than just use:
str.substring(0, str.length - 1)
string.reverse.substring(1).reverse
That's basically chop, right? If you're longing for a chop method, why not write your own StringUtils library and include it in your projects until you find a suitable, more generic replacement?
Hey, look, it's in commons.
Apache Commons StringUtils.
If you want just to remove the last character use .dropRight(1). Alternatively, if you want to remove a specific ending character you may want to use a match pattern as
val s: String = "hello!"
val sClean: String = s.takeRight(1) match {
case "!" => s.dropRight(1)
case _ => s
}

Resources