String split, when no space and having multiple space

Greetings,
i have 2 questions as new bee :
Q1. str =“123456” output should be > 123 456

Q2. newStr = " Good morning now 8.00 am and class start at 8.00 pm "
(i have spaces 3 4 5 4 2 4 2 3)
output should be > morning
output should be> 8.00 (for am)

what is be optimal way of doing it and why. Thank you in advance.

1 Like

Hi,

Q1
If you want to spilt string by number of character, perhaps you should use Substring method as the following.

str.Substring(0,3) returns 123
str.Substring(3) returns 456

Q2
Can you try Split method with StringSplitOptions.RemoveEmptyEntries as the following.

newStr.Split({" "c},StringSplitOptions.RemoveEmptyEntries)(3) returns 8.00

Regards,

5 Likes

For question one can we do regex? if yes then how should i write.

for question 2 i want “morning” too.

1 Like

Hi,

For question one can we do regex? if yes then how should i write.

System.Text.RegularExpressions.Regex.Match(str,"^.{3}").Value returns 123.

System.Text.RegularExpressions.Regex.Match(str,"(?<=^.{3}).*").Value returns 456.

for question 2 i want “morning” too.

str.Split({" "c},StringSplitOptions.RemoveEmptyEntries)(1)

Regards,

2 Likes

For Q1, I would rather rely on String.Format or ToString with culture aware formatting or use invariant culture as describe in SO answer inked below. This can handle number with any count of digits and will format decimal “point” if needed too.

For Q2, you can splt on multiple spaces (if I understood) with a regex:

result = System.Text.RegularExpressions.Regex.Split(myText, "\s+")

3 Likes

Thank you.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.