How to remove all characters from a string, except the integers?
matheus
matheus at gmail.com
Fri Mar 4 19:51:44 UTC 2022
On Thursday, 3 March 2022 at 23:46:49 UTC, H. S. Teoh wrote:
> ...
> This version doesn't even allocate extra storage for the
> filtered digits, since no storage is actually needed (each
> digit is spooled directly to the output).
OK but there is another problem, I tested your version and mine
and there is a HUGE difference in speed:
LDC 1.27.1, with -O2:
import std.datetime.stopwatch;
import std.stdio: write, writeln, writef, writefln;
import std;
void printStrTim(string s,StopWatch sw){
writeln("\nstr: ", s
,"\nTim(ms): ", sw.peek.total!"msecs"
,"\nTim(us): ", sw.peek.total!"usecs"
);
}
void main(){
auto sw = StopWatch(AutoStart.no);
string s, str = "4A0B1de!2C9~6";
int j;
sw.start();
for(j=0;j<1_000_000;++j){
s="";
foreach(i;str){
(i >= '0' && i <= '9') ? s~=i : null;
}
}
sw.stop();
printStrTim(s,sw);
s = "";
sw.reset();
sw.start();
for(j=0;j<1_000_000;++j){
s="";
s = str.filter!(ch => ch.isDigit).to!string;
}
sw.stop();
printStrTim(s,sw);
}
Prints:
str: 401296
Tim(ms): 306
Tim(us): 306653
str: 401296
Tim(ms): 1112
Tim(us): 1112648
-------------------------------
Unless I did something wrong (If anything please tell). By the
way on DMD was worse, it was like 5x slower in your version.
Matheus.
More information about the Digitalmars-d-learn
mailing list