How to remove all characters from a string, except the integers?

matheus matheus at gmail.com
Thu Mar 3 22:54:39 UTC 2022


On Thursday, 3 March 2022 at 21:03:40 UTC, H. S. Teoh wrote:
> ...
>
> ------
> void main() {
> 	string s = "blahblah123blehbleh456bluhbluh";
> 	auto result = s.filter!(ch => ch.isDigit).to!int;
> 	assert(result == 123456);
> }
> ------
>
> Problem solved.  Why write 6 lines when 3 will do?

Just because I'm a simple man. :)

I usually program mostly in C and when in D, I go in the same way 
but using features like: GC, strings, AA etc.

Of course your version is a D'ish way of handling things, and I 
can't contest it looks better visually. But if size was problem I 
could have written:

void main(){
     string s, str = "4A0B1de!2C9~6";
     foreach(i;str){
     	(i >= '0' && i <= '9') ? s~=i : null;
     }
     writeln(s);
}

Well still 1 line off, but I goes with my flow. I mean this 
example is a simple one, but usually I can see and understand 
what a code in C is doing (more) easily than D just looking at 
it. Don't even ask about C++, because I gave up. :)

Matheus.

PS: I spotted something on your code, you're converting the 
result to int, this can lead to a overflow depending the values 
in the string.


More information about the Digitalmars-d-learn mailing list