This is much better:
using static System.Console;
using System;
public class Program {
public static void Main() {
WriteLine(Abreviatte("Rafael Rodrigues Arruda de Oliveira"));
WriteLine(Abreviatte("Rafael Rodrigues Arruda De Oliveira"));
}
public static string Abreviatte(string nome) {
var meio = " ";
var nomes = nome.Split(' ');
for (var i = 1; i < nomes.Length - 1; i++) {
if (!nomes[i].Equals("de", StringComparison.OrdinalIgnoreCase) &&
!nomes[i].Equals("da", StringComparison.OrdinalIgnoreCase) &&
!nomes[i].Equals("do", StringComparison.OrdinalIgnoreCase) &&
!nomes[i].Equals("das", StringComparison.OrdinalIgnoreCase) &&
!nomes[i].Equals("dos", StringComparison.OrdinalIgnoreCase))
meio += nomes[i][0] + ". ";
}
return nomes[0] + meio + nomes[nomes.Length - 1];
}
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
I’ve eliminated variables and unnecessary allocations. Only do operations you need in your code, if you want to compare disregarding the letter box then compare like this, do not create a string for nothing and then compare it with something else.
Note that I would normally use StringBuilder
, But I’m considering that almost never more than four middle names, so concatenation is acceptable. And I’m also considering that you don’t need the maximum optimization, otherwise the correct would be to use Span
.
In the AP code and the other answer with LINQ, the comparison in each existing middle name are 8 allocations against one of my code, but it is possible to eliminate even this allocation with the techniques cited.
Allocating more doesn’t make the answers wrong, I’m just giving you a more efficient option. But allocation is something that greatly impairs execution, and what may not make a difference an hour is used in a big loop and causes a huge problem. No wonder that much of the C# and . NET improvements have turned to decrease allocations.
In fact for maximum performance should not use Split()
also and operate character by character, but in general this is not a requirement so also did not do it.
To avoid long discussions in the comments your conversation was moved to the chat and can proceed there by the link provided.
– Bacco
Perfect question, I was looking for something like that, thank you!
– Brewerton Santos