Saturday, September 20, 2014

Code Project: String Utility Conversion

Please click HERE to access this project solution file from GitHub.

The String Utility Conversion will take a String of hours, minutes, or seconds and convert it to milliseconds. The purpose is to demonstrate how to convert a string with an int + suffix string rolled into one, convert it into a useable int, and to convert its units. This can easily be changed into any needed units.

For example, if you needed a program to only put out meters, you could change all the values to length.. or any other unit.

In this particular console app, you would enter hours as an int + h like: "1h", minutes like "10m", "100s", or seconds as "60s". You can see in the screenshot below, you can change the string to any value with one of the mentioned suffixes (h, m, s). I have highlighted these points in yellow in the screenshot so it is simpler to find.

Another important aspect of this app is that is uses 2 methods.

  • C# Sample:
                    // Hours suffix scenario - h
                else if (myString.EndsWith("h"))
                {
                    myString = myString.TrimEnd(new char[] {'h'});
                    bool x = int.TryParse(myString, out num);
                    if (x)
                    {
                        num = num * 3600000;
                    }
                    
                }
    
  • Regex Sample:
                Regex regex = new Regex("\\b(\\d+)(ms|h|m|s)?\\b");
    
                MatchCollection matches = regex.Matches(myString);
    
                if (matches.Count == 1)
                {
                    Match match = matches[0];
    
                    if (match.Groups.Count == 3)
                    {
                        String numberString = match.Groups[1].Value;
                        String suffix = match.Groups[2].Value;
    
                        // Milliseconds
                        if (String.IsNullOrWhiteSpace(suffix) || "ms".Equals(suffix))
                        {
                            bool ableToParse = int.TryParse(numberString, out num);
                        }
                        // Hours
                        else if ("h".Equals(suffix))
                        {
                            bool ableToParse = int.TryParse(numberString, out num);
                            if (ableToParse)
                            {
                                num *= 3600000;
                            }
                        }