Quantcast
Channel: Fraction of the Blogosphere » string
Viewing all articles
Browse latest Browse all 5

c# .net split strings with math divrem using lambda linq

0
0

Recently I came across a nice alternative to loops using linq for evenly splitting a string using Math.DivRem.

The following example illustrates how this can be used to parse a sequence of numbers based on a time series which may give variable results in a custom messaging protocol.

(inspired by R. Prestol)

//not the complete classes but satisfies the below example
class message {
string series {get;set;}
}

  string[] series = message.series.Split(' '); //will NOT throw an exception if series string is empty
            int Rem = 0;
            int d = Math.DivRem(name.Length, 2, out Rem); //hardcoded two for simplicity in this example
 
//valueB will contain the same value as valueA if there is no second value in the sequence
            string valueA = string.Join(" ", sentence.Take(Math.Max(d, 1)).ToArray());
            string valueB = string.Join(" ", sentence.Skip(d).Take(d + Rem).ToArray());

int average = (Convert.ToInt32(valueA) + Convert.ToInt32(valueB)) / 2; //2 would also need to be dynamic here

Console.WriteLine(average.ToString());

//potential input
//100 101
//100

//output for average
//first input: 100
//second input: 100

A significant figure is lost (.5) on first input since valueA and valueB are converted to int. Conversion to decimal, double etc would of course maintain this detail depending on the rounding you are looking for.



Viewing all articles
Browse latest Browse all 5

Latest Images

Trending Articles





Latest Images