In kotlin how to use the '$' for argument index in the string for formatting.
i.e. would like put the same number 122 at first position and 3rd position of the string. In kotlin the string does not like the '$' for this.
(note: the strFormat are dynamically generated and can't be stored in the string resource file).
val strFormat = "%d, %s, same as 1st int: %1$d, same as 1st string: %1$s, $3$s"
val str = String.format(strFormat, 122, "the string one", "string two")
$ is a special kotlin metacharacter for string templates. You can use the string templating mechanism itself to insert a literal $:
${'$'}
Related
Let's say I have a string val s = "_1.2V_ADC"
The period is invalid for my use case so I need to replace it with another character, like p so the final string should be "_1p2V_ADC"
Is there any easy way to do that in Stanza?
You can use the replace function for this:
val s = replace("_1.2V_ADC", ".", "p")
It will replace all matches of the string "." with the string "p".
You need this function from the core package :
public defn replace (str:String, s1:String, s2:String) -> String
You example become replace("_1.2V_ADC", ".", "p")
That gives _1p2V_ADC
My program is something like that:
func = do
text <- getLine
return text
If I read line \123\456, the result is, naturally, \\123\\456.
How can I obtain \123\456 as the result?
Based on the discussion in comments, it looks like you want to parse the string as if it was a string literal, except that it is not surrounded by quotes.
We can make use of of read :: Read a => String -> a here that for a string parses it as if it was a string literal to a string. The only problem is that this string literal is surrounded by double quotes (").
We can thus add these quotes, and work with:
read ('"' : text ++ "\"") :: String
Not every string text is however per se a valid string literal, so the above might fail. For example if the text contains a double quote itself, that is not directly preceded by a backslash (\).
I am trying to escape string for new line i.e \n.
For example lets say string is:-
First Line Of String
second Line of String
Third Line of String
Now if i use String extension and say
func escapeString() -> String{
newString = self.stringByRemovingPercentEncoding
return newString
}
This extension does not give me newString as
First Line Of String\nSecond Line Of String\nThird Line Of String
I need above string as a jsonString to pass to server.i.e. i have to String encode it
Swift 5
You can use JSONEncoder to escape \n, \, \t, \r, ', " and etc. characters instead of manually replacing them in your string e.g.:
extension String {
var escaped: String {
if let data = try? JSONEncoder().encode(self) {
let escaped = String(data: data, encoding: .utf8)!
// Remove leading and trailing quotes
let set = CharacterSet(charactersIn: "\"")
return escaped.trimmingCharacters(in: set)
}
return self
}
}
let str = "new line - \n, quote - \", url - https://google.com"
print("Original: \(str)")
print("Escaped: \(str.escaped)")
Outputs:
Original: new line -
, quote - ", url - https://google.com
Escaped: new line - \n, quote - \", url - https:\/\/google.com
stringByRemovingPercentEncoding is for percent encoding as used in URLs, as you might expect from the name. (If not from that, maybe from reading the docs, the pertinent part of which even shows up in Xcode code completion.) That is, it takes a string like "some%20text%20with%20spaces" and turns it into "some text with spaces".
If you want to do a different kind of character substitution, you'll need to do it yourself. But that can still be a one-liner:
extension String {
var withEscapedNewlines: String {
return self.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
}
}
Note the first argument to self.stringByReplacingOccurrencesOfString is an escape code passed to the Swift compiler, so the actual value of the argument is the newline character (ASCII/UTF8 0x0A). The second argument escapes the backslash (in the text passed to the Swift compiler), so the actual value of the argument is the text \n.
I need to split a uint to a list of bits (list of chars, where every char is "0" or "1", is also Ok). The way I try to do it is to concatenate the uint into string first, using binary representation for numeric types - bin(), and then to split it using str_split_all():
var num : uint(bits:4) = 0xF; // Can be any number
print str_split_all(bin(num), "/w");
("/w" is string match pattern that means any char).
The output I expect:
"0"
"b"
"1"
"1"
"1"
"1"
But the actual output is:
0. "0b1111"
Why doesn't it work? Thank you for your help.
If you want to split an integer into a list of bits, you can use the %{...} operator:
var num_bits : list of bit = %{num};
You can find a working example on EDAPlayground.
As an extra clarification to your question, "/w" doesn't mean match any character. The string "/\w/" means match any single character in AWK Syntax. If you put that into your match expression, you'll get (almost) the output you want, but with some extra blanks interleaved (the separators).
Regardless, if you want to split a string into its constituting characters, str_split_all(...) isn't the way to go. It's easier to convert the string into ASCII characters and then convert those back to string again:
extend sys {
run() is also {
var num : uint(bits:4) = 0xF; // Can be any number
var num_bin : string = bin(num);
var num_bin_chars := num_bin.as_a(list of byte);
for each (char) in num_bin_chars {
var char_as_string : string;
unpack(packing.low, %{8'b0, char}, char_as_string);
print char_as_string;
};
};
};
The unpack(...) syntax is directly from the e Reference Manual, Section 2.8.3 Type Conversion Between Strings and Scalars or Lists of Scalars
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