Groovy Split on Delimiter and Join Through nth Element - groovy

I'm a little bit newer to Groovy and trying to find the best way to split a delimited string. For example I have a string:
1/2/3/4/5/6/7
and I want basically a substring of that. So if I wanted 5 of those values retaining the delimiter my desired result would be
1/2/3/4/5
I've tried the code below which works on my online compiler but not in my actual application. It throws this error "No signature of method: static java.util.Arrays.copyOfRange() is applicable for argument types: ([Ljava.lang.String;, java.lang.Integer, java.lang.Long)"
inputString = "1/2/3/4/5/6/7";
stringDepth = 5;
stringArray = Arrays.copyOfRange(inputString.split("/"), 0, stringDepth);
stringPath = stringArray.join('/');
println "inputString="+inputString;
println "stringDepth="+stringDepth;
println "stringPath="+stringPath;

inputString.split('/').take(stringDepth).join('/')
Should do it?

Related

How to Split a string with a set of delimiters and find what delimiter it was? Kotlin

So I am learning Kotlin now, and I was trying to do a calculator where if we can give expression like 4+3 or 3*5 and we will get the answer so I was trying to split that input string and then find what operator is used and what are the operands.
var list = str.split("+","-","*","/" )
so how can i get the delimiter that is used to split that string too.
I'm afraid that split method doesn't have this feature. You would have to split the the string via separate split calls. And compare the outcome with original string. If the string wasn't split by given delimiter that outcome should be the same.
Eg. like this:
var str = "5+1"
var delimiters = arrayOf("+","-","*","/")
var found = "Not found"
for (delimiter in delimiters) {
var splited = str.split(delimiter)
if(splited[0] != str) {
found = delimiter
break
}
}
println(found)

+ operator behaving unexpectedly in string concatenation in groovy [duplicate]

This question already has answers here:
What's wrong with Groovy multi-line String?
(3 answers)
Closed 7 years ago.
We have a habit of overriding the toString method so that we can just get fields value just by calling
println "Object details-->$object"
We thought to write test cases for our build as a good practice and to follow TDD.
My test case failed with some missing lines of data. Test case looks like below:
void "test method:toString"() {
given:
CSV csv = new CSV(accountId: '1', accountName: 'testName')
when:
String exp = "[accountId=" + csv.accountId + ", groupId)" + csv.groupId + ", accountName=" + csv.accountName +"]"
String string = csv.toString()
then:
string == exp
}
Below is my class:
public class CSV {
String accountId
String groupId
String accountName
String chargeMode
String invoiceId
String date
#Override
public String toString() {
return "ChargingCsvLine [accountId="
+ accountId + ", groupId)" + groupId + ", accountName="+
accountName + " "]"
}
}
Test case fails abruptly. Then I gave a careful look and tried with appending '+' in end of line break and not at start of line.
And test case worked properly.
Can anyone tell me whether it's a bug or groovy just accepted both the above cases but case of appending '+' in end of line is the only correct way.
To me it seems that correct way of concatenating using '+' is
"abc"+
"def"
and not
"abc"
+"def"
But why did groovy silently broke in that case and didn't throw any errors. At least operator level exception should be thrown.
Thanks!
Groovy takes your first line (without the ending +) and uses this a return statement and does not execute any further code.
String add1() {
return "1"
+ "2" // never gets executed
}
assert add1()=="1"
If there wheren't a return it would give you a runtime error:
String add1() {
"1" // one statement
+ "2" // another statement - this is the implicit return
}
assert add1()=="12"
And this fails with:
Caught: groovy.lang.MissingMethodException: No signature of method: java.lang.String.positive() is applicable for argument types: () values: []
Possible solutions: notify(), tokenize(), size(), size()
groovy.lang.MissingMethodException: No signature of method: java.lang.String.positive() is applicable for argument types: () values: []
Possible solutions: notify(), tokenize(), size(), size()
at tos.add1(tos.groovy:3)
at tos$add1.callCurrent(Unknown Source)
at tos.run(tos.groovy:6)
shell returned 1
The reason here is, that groovy sees two lines, and strings don't override the positive operator.
It also fails to compile, if static compilation is used:
#groovy.transform.CompileStatic
String add1() {
return "1"
+ "2"
}
assert add1()=="1"
Yields:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
test.groovy: 4: [Static type checking] - Cannot find matching method java.lang.String#positive(). Please check if the declared type is right and if the method exists.
# line 4, column 2.
+ "2"
^
1 error
Takeaways:
groovy has differences to java
don't generate toString in your IDE, when there is #ToString in groovy
don't bang strings together with + in groovy, when there are GStrings.
You can use triple single quotes for multi-lined commands in groovy.
http://www.groovy-lang.org/syntax.html#_string_concatenation
Triple single quoted strings are multiline. You can span the content of
the string across line boundaries without the need to split the string
in several pieces, without contatenation or newline escape characters:
def aMultilineString = '''line one
line two
line three'''

Create string without repeating the same element jn the string (Matlab)

I have a string "FDFACCFFFBDCGGHBBCFGE" . Could anyone help me to generate a new string with the same order but no element inside repeated twice. Thanks !
The expected output should be like this : "FDACBGHE"
Use unique with the 'stable'option:
str = 'FDFACCFFFBDCGGHBBCFGE';
result = unique(str, 'stable');
If you want something more manual: use bsxfun to build a logical index of the elements that haven't appeared (~any(...)) earlier (triu(..., 1)):
result = str(~any(triu(bsxfun(#eq, str, str.'), 1)));

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

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

Resources