How to split string with trailing empty strings in result? - scala

I am a bit confused about Scala string split behaviour as it does not work consistently and some list elements are missing. For example, if I have a CSV string with 4 columns and 1 missing element.
"elem1, elem2,,elem 4".split(",") = List("elem1", "elem2", "", "elem4")
Great! That's what I would expect.
On the other hand, if both element 3 and 4 are missing then:
"elem1, elem2,,".split(",") = List("elem1", "elem2")
Whereas I would expect it to return
"elem1, elem2,,".split(",") = List("elem1", "elem2", "", "")
Am I missing something?

As Peter mentioned in his answer, "string".split(), in both Java and Scala, does not return trailing empty strings by default.
You can, however, specify for it to return trailing empty strings by passing in a second parameter, like this:
String s = "elem1,elem2,,";
String[] tokens = s.split(",", -1);
And that will get you the expected result.
You can find the related Java doc here.

I believe that trailing empty spaces are not included in a return value.
JavaDoc for split(String regex) says: "This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array."
So in your case split(String regex, int limit) should be used in order to get trailing empty string in a return value.

Related

What is the fastest/easiest way to increase a number in a string variable in Powershell?

I have the following Powershell variable
$var = "AB-0045"
I would like to increase the number in the string to become "AB-0046".
I can do:
$newNumber = [int]$var.Substring($var.length -4,4) + 1
Which will give me the desired number 46, but then I have to append that 46 as a string to a new string "AB-00".
Is there a better way to do that?
Now that you have the integer, you'll have to convert back to string formatted in the way you'd like and concatenate.
I'd recommend adding to "AB-" rather than "AB-00" in case your number goes over 100.
To pad leading zeros, you can use the -f operator.
e.g. "{0:d4}" -f 45
You'll still need to get the integer first (45 in the example) from your original string.
I tested with regex class Replace() method and string class Split() method with string formatter. Split() seems faster provided your string is always in the same format. The Replace() method does not care what happens before the last 4 numbers:
# Replace Method
[regex]::Replace($var,'\d{4}$',{([int]$args[0].Value+1).ToString('0000')})
# Split method
$a,[int]$b = $var.split('-'); "{0}-{1:0000}" -f $a,++$b

How do I parse out a number from this returned XML string in python?

I have the following string:
{\"Id\":\"135\",\"Type\":0}
The number in the Id field will vary, but will always be an integer with no comma separator. I'm not sure how to get just that value from that string given that it's string data type and not real "XML". I was toying with the replace() function, but the special characters are making it more complex than it seems it needs to be.
is there a way to convert that to XML or something that I can reference the Id value directly?
Maybe use a regular expression, e.g.
import re
txt = "{\"Id\":\"135\",\"Type\":0}"
x = re.search('"Id":"([0-9]+)"', txt)
if x:
print(x.group(1))
gives
135
It is assumed here that the ids are numeric and consist of at least one digit.
Non-regex answer as you asked
\" is an escape sequence in python.
So if {\"Id\":\"135\",\"Type\":0} is a raw string and if you put it into a python variable like
a = '{\"Id\":\"135\",\"Type\":0}'
gives
>>> a
'{"Id":"135","Type":0}'
OR
If the above string is python string which has \" which is already escaped, then do a.replace("\\","") which will give you the string without \.
Now just load this string into a dict and access element Id like below.
import json
d = json.loads(a)
d['Id']
Output :
135

Flutter remove whitespace, commas, and brackets from List when going to display as a String

I want to go through my list of strings, and add it to a text element for display, but I want to remove the commas and remove the [] as well as the whitespace, but leave the symbols except the commas and brackets.
So if the List is.
[1,2,#3,*4,+5]
In the text field I want it to show - "12#3*4+5"
I can figure out how to display it, but Im using
Text(myList.tostring().replaceAll('[\\]\\,\\', '')
Is there a way to do this?
You should use the reduce method on your list.
List<String> myList = ["1", "2", "#3", "*4", "+5"];
String finalStr = myList.reduce((value, element) {
return value + element;
});
print(finalStr);
# output: "12#3*4+5"
This method reduces a collection to a single value by iteratively combining elements of the collection using the provided function.
The method takes a function that receives two parameters: one is the current concatenated value, which starts out with the value of the first element of your list, and the second parameter is the next element on your list. So you can do something with those two values, and return it for the next iterations. At last, a single reduced value is returned. In this case, using strings, the code in my answer will concatenate the values. If those were numbers, the result would be a sum of the elements.
If you want to add anything in between elements, simply use the return value. For instance, to separate the elements by comma and whitespace, it should look like return value + " ," + element;.
Unless I'm misunderstanding the question, the most obvious solution would be to use List.join().
List<String> myList = ["1", "2", "#3", "*4", "+5"];
print( myList.join() );
// Result
// 12#3*4+5
You could also specify a separator
print( myList.join(' ') );
// Result
// 1 2 #3 *4 +5

SSRS nested IIF/CStr explanation

Could someone let me know if the IIF statement below means output any value that starts with a 4 please?
=IIF(LEFT(CStr(Fields!CLOCK_NUMBER.Value),1)="4",Fields!JOB_NO.Value, "")
The short answer is yes.
Starting from the middle and working outwards this expression is doing the following..
Get the value of the field CLOCK_NUMBER
Convert this to a string (the CSTR function)
Take the 1st character (LEFT function with 1 as the seconds parameter)
If the equals "4" return the Value that is in JOB_NO
Otherwise return an empty string
If this is not working for some reason, try converting the job_no to a string before returning, that way you ensure you always return a string (in case JOB_NO is numeric). You can simply wrap the job_no in a CSTR like this CSTR(Fields!JOB_NO.Value)
Translates to..."try to" convert the field CLOCK_NUMBERS's native value to a string and take the LEFT(1) most significant digit(s) and if that value is "4" then return the JOB_NO Fields's value. else return empty string.
So, it is, if the first digit is 4 then return JOB_NO.

Perl's foreach with string argument

Perldocs only indicate that foreach loops "iterates over a normal list value" https://perldoc.perl.org/perlsyn.html#Foreach-Loops, but I sometimes see them with string arguments, such as the following examples:
foreach (`curl example.com 2>/dev/null`) {
# iterates 50 times
}
foreach ("foo\nbar\nbaz") {
# iterates just 1 time. Why?
}
Is the behavior of passing a string like this defined? Separately, why the disparate results from passing the string returned by a backticked command, and a literal string, as in the example?
In scalar context, backticks return a single scalar containing all the output of the enclosed command. But foreach (...) evaluates the backticks in list context, which will separates the output into a list with one line per element.
The question revolves around the context, a critical concept for many things in Perl.
The foreach loop needs a list to iterate over, so it imposes the list context to build the list values you saw mentioned in docs. The list may be formed with literals, qw(a b c), and may have one element; this is your second example, where one string is given, forming the one-element list that is iterated over.
The list can also come from an expression, that is evaluated in the list context; this is your first example. Many operations yield different returns based on context, and qx is such an operator as explained in mob's answer. This is something to note and be careful with. An expression may also return a single value regardless of context; then it is simply used to populate the list.
From perldoc -f qx:
In list context, returns a list of lines (however you've defined lines with $/ or $INPUT_RECORD_SEPARATOR), or an empty list if the command failed.
From perldoc perlsyn:
Compound statements
[...]
LABEL foreach VAR (LIST) BLOCK
A string is not a list. If you want to iterate over the characters in a string you'll need
foreach my $character (split('', "foo\nbar\nbaz")) {
I think you might be confusing Perl with Python:
>>> for c in "foo\nbar\nbaz":
... print c
...
f
o
.... remainder deleted ....
a
z
>>>
As pointed out by the other answers backticks/qx{} return a list of output lines from the executed command in list context.