You can split the string by matching sequences of digits or non-digits, then "forgetting" the matched characters with \K
.
preg_split[
'~[?:\d+|\D+]\K~',
$string,
0,
PREG_SPLIT_NO_EMPTY
]
Or you could use matched digits as the delimiter and retain the delimiters in the output.
preg_split[
'~[\d+]~',
$string,
0,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
]
A demonstration of both techniques.
If you know the order of your numeric and alphabetic substrings, then sscanf[]
is a perfect tool.
Code: [Demo]
var_export[sscanf['12jan', '%d%s']];
Output:
array [
0 => 12,
1 => 'jan',
]
Notice how 12
is conveniently cast as an integer as well.
sscanf[]
also allows individual variables to be assigned if desired [$day
and $month
] as the 3rd and 4th parameters.
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Given string str, divide the string into three parts one containing a numeric part, one containing alphabetic, and one containing special characters.
Examples:
Input : geeks01for02geeks03!!! Output :geeksforgeeks 010203 !!! Here str = "Geeks01for02Geeks03!!!", we scan every character and append in res1, res2 and res3 string accordingly. Input : **Docoding123456789everyday## Output :Docodingeveryday 123456789 **##
Steps :
- Calculate the length of the string.
- Scan every character[ch] of a string one by one
- if [ch is a digit] then append it in res1 string.
- else if [ch is alphabet] append in string res2.
- else append in string res3.
- Print all the strings, we will have one string containing a numeric part, other non-numeric part, and the last one contains special characters.
Implementation:
C++
#include
using
namespace
std;
void
splitString[string str]
{
string alpha, num, special;
for
[
int
i=0; i=
'A'
&& str[i] =
'a'
&& str[i]