Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I think I haven't seen this kind of problems yet when i searched the internet.

is there a way to seperate double and string when they are stored in a single string variable??

for example i have

C#
string blabla = "4.2 Minutes";


what I want to know is that for example. 4.2 will be stored in variable "numbers" and Minutes will be stored in variable "Letters".
is that possible?

What I have tried:

I have tried using Regex.

C#
string cutie = "4.5 Minutes";
Regex re = new Regex(@"([a-zA-Z]+)(\d+)");
Match result = re.Match(cutie);
string letters = result.Value;
string numbers = result.Value;


well something like this, tho it doesn't work.
Posted
Updated 31-Aug-17 9:29am
Comments
BillWoodruff 31-Aug-17 15:01pm    
Can you change the format of the string ? Can you assume the string is always in the same format ? Is using RegX a requirement ? Do you want to change the data into a TimeSpan ?

If want still want to use a regex try the following.
String blabla = "4.2 Minutes";

Regex regex = new Regex(@"^(?<NUMVALUE>\d*.\d*)\s*(?<STRVALUE>[A-Z][a-z]*)$", RegexOptions.Singleline);

Match match = regex.Match(blabla);

if(match.Success)
{
    String numbers = match.Groups["NUMVALUE"].Value;
    String letters = match.Groups["STRVALUE"].Value;

    Console.WriteLine(numbers);
    Console.WriteLine(letters);
}
else
{
    Console.WriteLine("Not matched");
}
 
Share this answer
 
v3
Hi,

To your example, above, do this:

C#
private bool is_double(string val)
{
    try
    {
        Convert.ToDouble(val);
        return true;
    }
    catch
    {
        return false;
    }
}

private void separate_word()
{
   string text = "4.2 Minutes";
   string[] arr = text.Split(' ');

   string letter, number;

    foreach(string item in arr)
    {
        if(this.is_double(item))
        {
            number = item;
        }
        else
        {
            letter = item;
        }
    }
}
 
Share this answer
 
v2
Comments
BillWoodruff 1-Sep-17 14:00pm    
this.is_double(item) ... this must be an error
Sheila Pontes 4-Sep-17 7:31am    
Hi,

What is the error?
For this specific format, you don't need regex. Just splitting on the space is sufficient:
C#
string blabla = "4.2 Minutes";
string[] split = blabla.Split(' ');
string letters = split[1];
string numbers = split[0];
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900