I would like to write some D code that would take a string, and split it by " ", but not "\ ". I normally use std.array.split for splitting, but it obviously can't handle this. What would be the best way to do what I want?
Regular expressions (+ lookbehind) is powerful enough for that:
import std.regex;
void main()
{
auto parts = split(r"foo bar\ bar baz", regex(r"(?<!\\) "));
assert(parts == ["foo", r"bar\ bar", "baz"]);
}
http://dlang.org/phobos/std_regex.html
Related
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.'
I'd like to indent a multiline string in Groovy but I can't figure out the right RegEx syntax / or Regex flags to achieve that.
Here's what I tried so far:
def s="""This
is
multiline
"""
println s.replaceAll('/(.*)/'," \1")
println s.replaceAll('/^/'," ")
println s.replaceAll('(?m)/^/'," \1")
println s.replaceAll('(?m)/(.*)/'," \1")
These didn't work as expected for some reason.
The only thing that worked so for is this block:
def indented = ""
s.eachLine {
indented = indented + " " + it + "\n"
}
println indented
Is there a shorter / more efficient way to indent all lines of a string in Groovy?
You need to put the (?m) directive inside the regular expression; and the pattern is a slashy string, not a single quoted string with slashes inside:
s.replaceAll(/(?m)^/, " ")
You could split and join - don't know if it's more efficient, but shorter
def s="""This
is
multiline
"""
def indent = " "
println indent + s.split("\\n").join("\n" + indent);
Or perhaps using just the replace function from java which is non-regex and potentially faster:
def s="""\
This
is
multiline
"""
println ' ' + s.replace('\n', '\n ')
which prints:
This
is
multiline
note: for those who are picky enough, replace does use the java regex implementation (as in Pattern), but a LITERAL regex which means that it will ignore all normal regex escapes etc. So the above is probably still faster than split for large strings, but this makes you wish they had left some function in there that just did a replace without any involvement of the potentially slow Pattern implementation.
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.
Is there a way to have a way to make a new line in swift like "\n" for java?
var example: String = "Hello World \n This is a new line"
You should be able to use \n inside a Swift string, and it should work as expected, creating a newline character. You will want to remove the space after the \n for proper formatting like so:
var example: String = "Hello World \nThis is a new line"
Which, if printed to the console, should become:
Hello World
This is a new line
However, there are some other considerations to make depending on how you will be using this string, such as:
If you are setting it to a UILabel's text property, make sure that the UILabel's numberOfLines = 0, which allows for infinite lines.
In some networking use cases, use \r\n instead, which is the Windows newline.
Edit: You said you're using a UITextField, but it does not support multiple lines. You must use a UITextView.
Also useful:
let multiLineString = """
Line One
Line Two
Line Three
"""
Makes the code read more understandable
Allows copy pasting
You can use the following code;
var example: String = "Hello World \r\n This is a new line"
You can do this
textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"
The output will be
Name: output of string1
Phone Number: output of string2
"\n" is not working everywhere!
For example in email, it adds the exact "\n" into the text instead of a new line if you use it in the custom keyboard like: textDocumentProxy.insertText("\n")
There are another newLine characters available but I can't just simply paste them here (Because they make a new lines).
using this extension:
extension CharacterSet {
var allCharacters: [Character] {
var result: [Character] = []
for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
result.append(Character(uniChar))
}
}
}
return result
}
}
you can access all characters in any CharacterSet. There is a character set called newlines. Use one of them to fulfill your requirements:
let newlines = CharacterSet.newlines.allCharacters
for newLine in newlines {
print("Hello World \(newLine) This is a new line")
}
Then store the one you tested and worked everywhere and use it anywhere.
Note that you can't relay on the index of the character set. It may change.
But most of the times "\n" just works as expected.
I have a list that I want to print:
foo: list of string;
I want to create a string bar that is the concatenation of the elements of foo. In Perl I would do:
$bar = join " ", #foo;
The only way I can think of to do this in specman is:
var bar: string = "";
for each in foo {
bar = appendf("%s %s", bar, it);
};
This seems like it would have very poor performance, because it copies bar onto itself for each element in foo. Is there any better way to do this?
There is also a dedicated function for this:
str_join(list: list of string, separator: string) : string
I'm sure help str_join will give you the details. There are also other useful functions like str_match, str_split which you may like.
As an additional hint, maybe you should print yourself the e Language Quick Reference, see http://www.cadence.com/Community/blogs/fv/archive/2009/06/19/send-us-suggestions-for-updating-the-e-specman-quick-reference-card.aspx.
While writing the question I stumbled across the to_string() method. I can use:
var bar: string = foo.to_string();
This is the equivalent of Perl's:
$bar = join "\n", #foo;
If I want to use spaces I can use:
var bar: string = str_replace(foo.to_string(), "\n", " ");