fork download
  1. using static System.Console;
  2.  
  3. public class Test {
  4. public static void Main() {
  5. const int MaxTamanhoEndereco = 30;
  6. WriteLine(TrimPosition("AvenidaAventureirosAfortunados, 1234", MaxTamanhoEndereco));
  7. WriteLine(TrimPosition("Rua Aventureiros Afortunados, 12345", MaxTamanhoEndereco));
  8. WriteLine(TrimPosition("Av Aventureiros Afortunados, 12345", MaxTamanhoEndereco));
  9. WriteLine(TrimPosition("R Aventureiros Afortunados, 12345", MaxTamanhoEndereco));
  10. WriteLine(TrimPosition(" Aventureiros Afortunados, 12345", MaxTamanhoEndereco));
  11. WriteLine(TrimPosition("Aventureiros Afortunados, 12345", MaxTamanhoEndereco));
  12. WriteLine(TrimPosition("Aventureiros Afortunados, 1234", MaxTamanhoEndereco));
  13. }
  14. static string TrimPosition(string text, int limit, string specialChars = " ,.", string trimMarker = "...") {
  15. if (text.Length > limit) {
  16. var markerLength = trimMarker.Length;
  17. var isSpecial = specialChars.Contains(text.Substring(limit - markerLength, 1));
  18. text = text.Substring(0, limit - markerLength);
  19. var posicaoUltimoEspaco = text.LastIndexOfAny(specialChars.ToCharArray());
  20. text = ((posicaoUltimoEspaco > 0 && !isSpecial) ? text.Substring(0, posicaoUltimoEspaco) : text) + trimMarker;
  21. }
  22. return text;
  23. }
  24. }
  25.  
  26. //https://pt.stackoverflow.com/q/114959/101
  27.  
Success #stdin #stdout 0.04s 24396KB
stdin
Standard input is empty
stdout
AvenidaAventureirosAfortuna...
Rua Aventureiros...
Av Aventureiros Afortunados...
R Aventureiros Afortunados,...
 Aventureiros Afortunados,...
Aventureiros Afortunados,...
Aventureiros Afortunados, 1234