Thread overview
How can I directly reffer literal element itself inside [] slice?
Jan 11, 2021
Marcone
Jan 11, 2021
Marcone
Jan 11, 2021
oddp
Jan 11, 2021
Marcone
Jan 11, 2021
Paul Backus
Jan 11, 2021
Marcone
January 11, 2021
I can reffer length of literal string using $.

"Hello World"[0..$]

But I want make like it witout use variable name.

"Hello World"[0..?.indexOf("o")]
January 11, 2021
I am using it:


// Tipo Nulo.
class None {}

// Função slice()
auto slice(T1, T2, T3 = None)(T1 conteudo, T2 inicio, T3 fim = T3.init) {
	int start, end, startlen;
	static if (is(T2 == int)) {inicio = inicio < 0 ? conteudo.length + inicio : inicio;}
	static if (is(T3 == int)) {fim = fim <= 0 ? conteudo.length + fim : fim;}
	static if (is(T2 == int)) {start = inicio;} else static if (is(T2 == string)){start = conteudo.countUntil(inicio);}
	static if (is(T2 == string)) {static if (is(T1 == string)){startlen = start + inicio.length + 1;} else {startlen = start + 1;}}
	static if (is(T3 == int)) {end = fim;} else static if (is(T3 == string)){end = startlen + conteudo[startlen..$].countUntil(fim);}
	static if (is(T3 == None)) {return conteudo[start];} else {return conteudo[start..end];}
}
January 11, 2021
On 11.01.21 16:45, Marcone via Digitalmars-d-learn wrote:
> "Hello World"[0..?.indexOf("o")]

Does until [1] do the trick?

"Hello World".until("o") // => "Hell"

[1] https://dlang.org/library/std/algorithm/searching/until.html
January 11, 2021
On Monday, 11 January 2021 at 16:41:03 UTC, oddp wrote:
> On 11.01.21 16:45, Marcone via Digitalmars-d-learn wrote:
>> "Hello World"[0..?.indexOf("o")]
>
> Does until [1] do the trick?
>
> "Hello World".until("o") // => "Hell"
>
> [1] https://dlang.org/library/std/algorithm/searching/until.html

I want more support inside slice []
January 11, 2021
On Monday, 11 January 2021 at 15:45:51 UTC, Marcone wrote:
>
> I can reffer length of literal string using $.
>
> "Hello World"[0..$]
>
> But I want make like it witout use variable name.
>
> "Hello World"[0..?.indexOf("o")]

The exact syntax you want is impossible. The closest you can get is to use an `enum` constant, which is essentially a named literal:

enum hello = "Hello World";
writeln(hello[0 .. hello.countUntil("o")]); // "Hell"
January 11, 2021
On Monday, 11 January 2021 at 21:01:57 UTC, Paul Backus wrote:
> On Monday, 11 January 2021 at 15:45:51 UTC, Marcone wrote:
>>
>> I can reffer length of literal string using $.
>>
>> "Hello World"[0..$]
>>
>> But I want make like it witout use variable name.
>>
>> "Hello World"[0..?.indexOf("o")]
>
> The exact syntax you want is impossible. The closest you can get is to use an `enum` constant, which is essentially a named literal:
>
> enum hello = "Hello World";
> writeln(hello[0 .. hello.countUntil("o")]); // "Hell"

I don't want use enum, I want use literal.