www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How can I directly reffer literal element itself inside [] slice?

reply Marcone <marcone email.com> writes:
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")]
Jan 11 2021
next sibling parent Marcone <marcone email.com> writes:
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];}
}
Jan 11 2021
prev sibling next sibling parent reply oddp <oddp posteo.de> writes:
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
Jan 11 2021
parent Marcone <marcone email.com> writes:
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 []
Jan 11 2021
prev sibling parent reply Paul Backus <snarwin gmail.com> writes:
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"
Jan 11 2021
parent Marcone <marcone email.com> writes:
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.
Jan 11 2021