Lets say I have a long string, and putting it on one line would decrease the readability.
This is would be the solution and it works:
def string = "This is a very\
long string"
But what if im in a Method or an if Statement were the lines are already indented. Then i would have to put the second part of the string like this which isnt very readable.
if (condition) {
def string = "This is a very\
long string"
}
How can i make the output look like this:
This is a very long string
With something like this:
if (condition) {
def string = "This is a very\
long string"
}
If you would want to have the line breaks, there is stripMargin to
help with removal of leading white space (at least until groovy supports
the new multi-line string literals from Java).
But since you don't want the line breaks, I'd just "add" the strings.
This usually is a no-no, because strings are immutable in java and this
will create intermediate instances. Yet then the compiler
should be able to optimize that, if you just add up string
literals (the (dynamic) groovy compiler 4.x does not). But then again,
it might not matter. And if you only want to pay once, make that
a public static final String MY_CONST_STRING = ... somewhere.
if (1) {
println "This is a very " +
"long string " +
"and more"
}
How can i make the output look like this:
This is a very long string
The code you show in the question is an idiomatic way to do it if you really need/want the literal definition to span lines in the source file without including a newline character in the literal:
def string = "This is a very \
long string"
You could also do something like this:
def string = '\
this is a \
very long string.'
Related
I have a raw string literal which is very long. Is it possible to split this across multiple lines without adding newline characters to the string?
file.write(r#"This is an example of a line which is well over 100 characters in length. Id like to know if its possible to wrap it! Now some characters to justify using a raw string \foo\bar\baz :)"#)
In Python and C for example, you can simply write this as multiple string literals.
# "some string"
(r"some "
r"string")
Is it possible to do something similar in Rust?
While raw string literals don't support this, it can be achieved using the concat! macro:
let a = concat!(
r#"some very "#,
r#"long string "#,
r#"split over lines"#);
let b = r#"some very long string split over lines"#;
assert_eq!(a, b);
It is possible with indoc.
The indoc!() macro takes a multiline string literal and un-indents it at compile time so the leftmost non-space character is in the first column.
let testing = indoc! {"
def hello():
print('Hello, world!')
hello()
"};
let expected = "def hello():\n print('Hello, world!')\n\nhello()\n";
assert_eq!(testing, expected);
Ps: I really think we could use an AI that recommend good crates to Rust users.
I saw this piece of code in the Groovy tutorial -
import groovy.sql.Sql
sql = Sql.newInstance( 'jdbc:jtds:sqlserver://serverName/dbName-CLASS;domain=domainName', 'username', 'password', 'net.sourceforge.jtds.jdbc.Driver' )
sql.eachRow( 'select * from tableName' ) { println "$it.id -- ${it.firstName} --" }
And it is the first occurrence of Groovy expressions (anything inside a ${} gets evaluated as an expression, not a string). My question is, does this Groovy expression feature actually provide some new functionality? It seems to me like there is nothing here that can be done with a good old string concat. IE -
println it.id + " -- " + it.firstName + " --"
Yes. That's what they are. Being able to add code and variables into strings is a feature of Groovy that make Groovy groovy. String in Groovy can be just like templates.
Now, Groovy strings are enclosed in (") quotes. But a standard Java String in Groovy is enclosed in an apostrophe ('). Standard Java strings in groovy cannot contain variable references or code.
It makes code easier to read. Sometimes looking at all the '+' signs in Java as part of string concatenation is a PITA.
What would you rather code and read:
println "$it.id -- ${it.firstName} --"
or
println it.id + " -- " + it.firstName + " --"
Now, with local variables it becomes much easier to read too:
Groovy
def name = "some name"
def age = 30
def waist = 42
println "Did $name really have a size $waist waist at age $age?"
Java:
String name = "some name";
int age = 30;
int waistSize = 42;
System.out.println("Did " + name + " really have a " + waist + " waist at age " age + "?";
Another thing you can do with them is use them as slightly Lazy Templates, ie:
def x = "abc"
// Closure expansion rather than variable
def s = "x: ${->x}"
// Prints 'x: abc'
println s
// Change x
x = 400
// Prints 'x: 400'
println s
With the pure String concatenation, you'd end up writing a print function, or repeating your concatenation code
Also, don't forget the multi-line string operators -- such as """ -- and the stripMargin method which allows you to :
def (name,age,sender) = [ 'Alice', 30, 'Tim' ]
println """Hello $name
|
|$age today? Congratulations!
|
|$sender""".stripMargin()
Which prints:
Hello Alice
30 today? Congratulations!
Tim
Again, could be done with String concatenation, but ends up being loads more typing and error prone (imo)
Lots more about Groovy strings (various flavours) here: http://groovy.codehaus.org/Strings+and+GString
I believe any string of the form "a string" (i.e. double quotes) is an instance of GString in Groovy (not String). It is GString that provides these extra capabilities.
With the accepted answer here we seem to have landed on the conclusion that, yes, GString (i.e. a double-quoted string with one or more ${<expr>} expressions) is just syntax sugar. (I'm going by the first sentence of the accepted answer: "Yes. That's what they are.")
But that seems to be wrong because of lazy evaluation, as noted above by tim_yates.
Expanding a bit on the above, if one or more expressions in the string are closures, they are only evaluated when toString() is called on the GString. So, in groovyconsole:
def stime = "The time is: ${-> new Date().getTime()}."
println stime
Thread.sleep(500)
println stime
The time is: 1384180043679.
The time is: 1384180044194.
How would you do this with + without creating a new string every time? (The answer, in two Java projects I've worked on, was to invent a Template.java class, to do this sort of thing.) This suggests to me that there is more than just syntax sugar. Or perhaps that it is syntax sugar - but for the GString class, not for java.lang.String or strings generally.
Another example:
def vals = ['a':42]
def tmpl = "The answer is ${-> vals.a}."
println tmpl
vals.a = 43
println tmpl
The answer is 42.
The answer is 43.
I'm not sure I actually like this feature of GString; I'm sort of used to strings being immutable (coming from Java). Groovy's strings are not (quite). It seems like you ought to be able to assume that if two Groovy 'strings' reference the same instance, they will have the same textual value, but that is not quite true.
http://groovy.codehaus.org/Strings+and+GString (about halfway down)
I'm trying to do a function in Lua that swaps the characters in a string.
Can somebody help me ?
Here is an example:
Input = "This LIBRARY should work with any string!"
Result = "htsil biaryrs ohlu dowkrw ti hna ytsirgn!"
Note: The space is also swapped
Thank You Very Much :)
The simplest and clearest solution is this:
Result = Input:gsub("(.)(.)","%2%1")
This should do it:
input = "This LIBRARY should work with any string!"
function swapAlternateChars(str)
local t={}
-- Iterate through the string two at a time
for i=1,#str,2 do
first = str:sub(i,i)
second = str:sub(i+1,i+1)
t[i] = second
t[i+1] = first
end
return table.concat(t)
end
print(input)
print(swapAlternateChars(input))
Prints:
This LIBRARY should work with any string!
hTsiL BIARYRs ohlu dowkrw ti hna ytsirgn!
If you need the output as lower case you could always end it with:
output = swapAlternateChars(input)
print(string.lower(output))
Note, in this example, I'm not actually editing the string itself, since strings in Lua are immutable. Here's a read: Modifying a character in a string in Lua
I've used a table to avoid overhead from concatenating to a string because each concatenation may allocate a new string in memory.
def a = "a string"
def b = 'another'
Is there any difference? Or just like javascript to let's input ' and " easier in strings?
Single quotes are a standard java String
Double quotes are a templatable String, which will either return a GString if it is templated, or else a standard Java String. For example:
println 'hi'.class.name // prints java.lang.String
println "hi".class.name // prints java.lang.String
def a = 'Freewind'
println "hi $a" // prints "hi Freewind"
println "hi $a".class.name // prints org.codehaus.groovy.runtime.GStringImpl
If you try templating with single quoted strings, it doesn't do anything, so:
println 'hi $a' // prints "hi $a"
Also, the link given by julx in their answer is worth reading (esp. the part about GStrings not being Strings about 2/3 of the way down.
My understanding is that double-quoted string may contain embedded references to variables and other expressions. For example: "Hello $name", "Hello ${some-expression-here}". In this case a GString will be instantiated instead of a regular String. On the other hand single-quoted strings do not support this syntax and always result in a plain String. More on the topic here:
http://docs.groovy-lang.org/latest/html/documentation/index.html#all-strings
I know this is a very old question, but I wanted to add a caveat.
While it is correct that single (or triple single) quotes prevent interpolation in groovy, if you pass a shell command a single quoted string, the shell will perform parameter substitution, if the variable is an environment variable. Local variables or params will yield a bad substitution.
I'm embedding JRuby in Java, because I need to call some Ruby methods with Java strings as arguments. The thing is, I'm calling the methods like this:
String text = ""; // this can span over multiple lines, and will contain ruby code
Ruby ruby = Ruby.newInstance();
RubyRuntimeAdapter adapter = JavaEmbedUtils.newRuntimeAdapter();
String rubyCode = "require \"myscript\"\n" +
"str = build_string(%q~"+text+"~)\n"+
"str";
IRubyObject object = adapter.eval(ruby, codeFormat);
The thing is, I don't know what strings I can use as delimiters, because if the ruby code I'm sending to build_string will contain ruby code. Right know I'm using ~,but I think this could break my code. What characters can I use as delimiters to make sure my code will work no matter what the ruby code is?
use the heredoc format:
"require \"myscript\"\n" +
"str = build_string(<<'THISSHOUDLNTBE'\n" + text + "\nTHISSHOULDNTBE\n)\n"+
"str";
this however assumes you won't have "THISSHOULDNTBE" on a separate line in the input.
Since string text contain contain any character, there is no character left to use for quotation escaping like the ~ you're using now. You would still need to escape the tilde in string text in java and append that one to the string you're building.
Something like (untested, not a Java guru):
String rubyCode = "require \"myscript\"\n" +
"str = build_string(%q~" + text.replaceAll("~", "\\~") + "~)\n"+
"str";