Auo
Auo

Reputation: 409

Efficient way to Splitting a string

I want to split the following string to get the values, what is the neatest and efficient way to do that.

String Maturity = "0=Child|13=Teen|18=Adult";

I have tried the following but not sure if that is the best way.

string[] Configuration = Maturity.Split('|');
Int64 childAgeMin, teenAgeMin, adultAgeMin;
childAgeMin = Convert.ToInt64(Configuration[0].Substring(0,         Configuration[0].IndexOf("=")));
teenAgeMin = Convert.ToInt64(Configuration[1].Substring(0, Configuration[1].IndexOf("=")));
adultAgeMin = Convert.ToInt64(Configuration[2].Substring(0, Configuration[2].IndexOf("=")));

which I am going to later use as

 if (Age >= childMinAge && Age < teenMinAge)

            Maturity = "Child";

        else if (Age >= teenMinAge && Age < adultMinAge)

            Maturity = "Teen";

        else if (Age >= adultMinAge) 

            Maturity = "Adult";

Thank you for your help in advance

Upvotes: 1

Views: 82

Answers (3)

Vecchiasignora
Vecchiasignora

Reputation: 1315

try this

string str = "0=Child|13=Teen|18=Adult";
            List<string> seplist = str.Split('|').ToList();
            int Age = 14;
            string Maturity = string.Empty;
            foreach (var item in seplist)
            {
                var part = item.Split('=');
                if (int.Parse(part.First()) <= Age)
                    Maturity = part.Last();
                else
                {
                    if (int.Parse(part.First()) > Age)
                        break;
                }
            }
            Console.WriteLine(Maturity);
            Console.ReadLine();

Upvotes: 0

Dan Lewi Harkestad
Dan Lewi Harkestad

Reputation: 145

What you have is efficient enough, really. In this context almost anything you could dream up is efficient enough, but for neatness? Well, I would've at least refactored the conversion into a function, and do you really need a long int to store the age levels? I doubt it as humans generally don't become that old. I would just go for a regular int.

Something like this:

int ConvertFromMaturityConfig(string maturityConfig)
{
    string ageString = maturityConfig.Split('=')[0];
    return int.Parse(ageString);
}

Usage:

string maturity = "0=Child|13=Teen|18=Adult";
string[] configuration = maturity.Split('|');

int childAgeMin = ConvertFromMaturityConfig(configuration[0]);
int teenAgeMin = ConvertFromMaturityConfig(configuration[1]);
int adultAgeMin = ConvertFromMaturityConfig(configuration[2]);

I would also consider trying to determine which configuration belongs to which value. As it is, you're expecting you get the child age, the teen age and the adult age, in that order. Personally, with the constraints you have, I would've put it into a dictionary so that you could look it up there. Then you could have something like this:

string maturity = "0=Child|13=Teen|18=Adult";
var config = maturity.Split('|')
    .Select(s => s.Split('='))
    .ToDictionary(
        c => c[1], // key selector
        c => int.Parse(c[0]));

Then you can use it like this:

if (age >= config["Child"] && age < config["Teen"])
    maturity = "Child";
else if (age >= config["Teen"] && age < config["Adult"])
    maturity = "Teen";
else if (age >= config["Adult"]) 
    maturity = "Adult";

You would be wise to consider what happens if the age is below the minimum child age, by the way.

Upvotes: 1

CodingYoshi
CodingYoshi

Reputation: 27039

Create a class like below:

public class PersonRecord
{
   public int MinAge { get; set; }
   public string Maturity { get; set; }
}

Create a method which will parse the string like below:

public static List<PersonRecord> Parse(string records)
{
   var splits = records.Split('|');
   var persons = splits.Select(p =>
   {
      int age;
      var split = p.Split('=');
      if(int.TryParse(split[0], out age))
      {
         return new PersonRecord { MinAge = age, Maturity = split[1] };
      }

      // Age was not a number so so whatever you want here
      // Or you can return a dummy person record
      throw new InvalidOperationException("Records is not valid.");

   }).ToList();

   return persons;
}

Use it like this:

string records = "0=Child|13=Teen|18=Adult";
var persons = Parse(records);

var p1Maturity = persons[0].Maturity;

Performance

Choose usability and code clarity firstly. Do not worry about performance if it is not an issue yet. Do performance testing and if the above code is the bottleneck then you can optimize it.


Possible Enhancements

You can add another property to the PersonRecord class MaxAge if you need/want and more methods and properties depending on your needs.

Upvotes: 1

Related Questions