| |
| Posted by H. S. Teoh in reply to matheus | PermalinkReply |
|
H. S. Teoh
Posted in reply to matheus
| On Thu, Mar 03, 2022 at 10:54:39PM +0000, matheus via Digitalmars-d-learn wrote:
> 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);
> > }
> > ------
[...]
> 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.
If you need to, convert to long instead.
Or if you want a string for subsequent manipulation, replace `int` with `string`.
Or, if you don't actually need to manipulate the value at all, but just print the digits, then it becomes even simpler:
void main() {
string s = "blahblah123blehbleh456bluhbluh";
writeln(s.filter!(ch => ch.isDigit));
}
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).
T
--
The peace of mind---from knowing that viruses which exploit Microsoft system vulnerabilities cannot touch Linux---is priceless. -- Frustrated system administrator.
|