Thread overview | |||||
---|---|---|---|---|---|
|
December 05, 2019 Slice/Substr [0..?lastIndexOf(".")] How refer itself without create a variable? | ||||
---|---|---|---|---|
| ||||
Simple example: writeln("Hi\nHow are you?\nGood".splitLines()[0][0..?lastIndexOf(r"\")]); How to refer to this string in lastIndexOf() without create a variable? Thank you. |
December 05, 2019 Re: Slice/Substr [0..?lastIndexOf(".")] How refer itself without create a variable? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Marcone | On Thursday, 5 December 2019 at 11:28:51 UTC, Marcone wrote:
> Simple example:
>
> writeln("Hi\nHow are you?\nGood".splitLines()[0][0..?lastIndexOf(r"\")]);
>
> How to refer to this string in lastIndexOf() without create a variable?
>
> Thank you.
One solution:
writeln(
"Hello\nHow are you?\nGood"
.splitLines()
.map!(x => x[0..x.lastIndexOf("o")])
);
But be careful: lastIndexOf could be < 0 if string is not found.
|
December 05, 2019 Re: Slice/Substr [0..?lastIndexOf(".")] How refer itself without create a variable? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Marcone | On Thursday, 5 December 2019 at 11:28:51 UTC, Marcone wrote: > Simple example: > > writeln("Hi\nHow are you?\nGood".splitLines()[0][0..?lastIndexOf(r"\")]); > > How to refer to this string in lastIndexOf() without create a variable? > > Thank you. .splitLines[0] already just produces "Hi", containing no "\", so this example is a bit broken. writeln("#", "Hi\nHow are you?\nGood".splitLines()[0], "#"); // #Hi# You could write a function to work around having to declare a variable: string upto(string input, string delim) { return input[0 .. input.countUntil(delim)]; } void main() { writeln(upto("Up to colon: skip this", ":")); // Up to colon writeln("Up to colon: skip this".upto(":")); // Up to colon } You can use a function literal or lambda, but it isn't pretty: writeln((string s){return s[0..s.countUntil(":")];}("Up to colon: skip this")); // Up to colon writeln((s => s[0..s.countUntil(":")])("Up to colon: skip this")); // Up to colon Bastiaan. |
Copyright © 1999-2021 by the D Language Foundation