martedì 17 gennaio 2012

How To: Get Center of a String.

Un collega mi ha chiesto come trovare il carattere centrale di una stringa, di contro la richiesta è semplice, ma ci sono vari modi per ottenere lo stesso risultato.

In alcuni casi ci si può fare del male, in altri si può sperare che con un colpo vada tutto bene...

C'e' da ricordarsi "sempre" che una string è comunque un array di char e quindi ...

class Program
{
static void Main(string[] args)
{
string test = " abcdefghilmnopqrstuvz ";

//Complesso ma non troppo
int c = Convert.ToInt32(
test.TrimStart(
new char[] { ' ' }
).TrimEnd(
new char[] { ' ' }
).ToCharArray().Length / 2);

char res = test.TrimStart(
new char[] { ' ' }
).TrimEnd(
new char[] { ' ' }
).ToCharArray()[c];

//Semi "professional"
int c1 = Convert.ToInt32(
test.Trim().ToCharArray().Length / 2);

char res1 = test.Trim().ToCharArray()[c1];


// Pro
int c2 = Convert.ToInt32(
test.Replace(" ","").ToCharArray().Length / 2);

char res2 = test.Trim().ToCharArray()[c2];



Console.WriteLine(res);
Console.WriteLine(res1);
Console.WriteLine(res2);

// ADVANCED !!
Console.WriteLine(test.Trim()[Convert.ToInt32(test.Length / 2)]);
Console.ReadKey();
}
}


Quindi ecco alcune possibili soluzioni.

Il problema generalmente non sta nel non sapere le cose, ma nel non chiedere !

Nessun commento: