elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Guía actualizada para evitar que un ransomware ataque tu empresa


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [APORTE] Contar agrupaciones "()[]" en un String, obtener indices, y más...
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [APORTE] Contar agrupaciones "()[]" en un String, obtener indices, y más...  (Leído 1,451 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.821



Ver Perfil
[APORTE] Contar agrupaciones "()[]" en un String, obtener indices, y más...
« en: 28 Junio 2014, 07:57 am »

Bueno pues empecé haciendo un código muy sencillo (quiero decir, muy pequeño) y acabé expandiendo su funcionalidad...

Se trata de una función que cuenta los caracteres de agrupación dentro de un String, comprueba si hay agrupaciones abiertas o vacias, y la cantidad de agrupaciones abiertas y cerradas hay, y obtiene sus índices de posición en el string, la función devuelve todos estos datos gracias a una Class personalizado para la ocasión.

No es gran cosa, simplemente quise compartirlo.

Espero que a alguien le ayude.

Código
  1.    ' Count Agrupations In String
  2.    ' // By Elektro
  3.    '
  4.    ' Example Usages :
  5.    '
  6.    'Private Sub Test()
  7.    '
  8.    '    Dim InputStrings As String() =
  9.    '        {
  10.    '            "(This) is (good)",
  11.    '            "This (is (good))",
  12.    '            "This is good",
  13.    '            "This is (bad))",
  14.    '            "This is (bad",
  15.    '            "This is bad)",
  16.    '            "This is bad)("
  17.    '        }
  18.    '
  19.    '    Dim AgrupationChars As New Tuple(Of Char, Char)("(", ")")
  20.    '
  21.    '    For Each InputString As String In InputStrings
  22.    '
  23.    '        Dim Info As AgrupationCharsInfo = Me.CountAgrupationsInString(AgrupationChars, InputString)
  24.    '
  25.    '        Dim sb As New System.Text.StringBuilder
  26.    '
  27.    '        With sb
  28.    '
  29.    '            .AppendLine(String.Format("Input String: {0}", Info.InputString))
  30.    '            .AppendLine(String.Format("Agrupation Characters: {0}{1}", Info.AgrupationChars.Item1,
  31.    '                                                                       Info.AgrupationChars.Item2))
  32.    '
  33.    '            .AppendLine()
  34.    '            .AppendLine(String.Format("String has closed agrupations?: {0}", Info.StringHasClosedAgrupations))
  35.    '            .AppendLine(String.Format("String has opened agrupations?: {0}", Info.StringHasOpenedAgrupations))
  36.    '
  37.    '            .AppendLine()
  38.    '            .AppendLine(String.Format("Closed Agrupations Count: {0}", Info.CountClosedAgrupations))
  39.    '            .AppendLine(String.Format("Opened Agrupations Count: {0}", Info.CountOpenedAgrupations))
  40.    '
  41.    '            .AppendLine()
  42.    '            .AppendLine("Closed Agrupations Indexes:")
  43.    '            For Each Item As Tuple(Of Integer, Integer) In Info.ClosedAgrupationsIndex
  44.    '                .AppendLine(String.Format("Start: {0}, End: {1}",
  45.    '                                          CStr(Item.Item1), CStr(Item.Item2)))
  46.    '            Next Item
  47.    '
  48.    '            .AppendLine()
  49.    '            .AppendLine(String.Format("Opened Agrupations Indexes: {0}",
  50.    '                                      String.Join(", ", Info.OpenedAgrupationsIndex)))
  51.    '
  52.    '        End With '/ sb
  53.    '
  54.    '        MessageBox.Show(sb.ToString, "Agrupations Information",
  55.    '                        MessageBoxButtons.OK, MessageBoxIcon.Information)
  56.    '
  57.    '    Next InputString
  58.    '
  59.    'End Sub
  60.  
  61.    ''' <summary>
  62.    ''' Retrieves info about the closed and opened agrupation characters inside a String.
  63.    ''' </summary>
  64.    ''' <param name="AgrupationChars">Indicates the characters to determine agrupations.</param>
  65.    ''' <param name="InputString">Indicates the string where to count the agrupations.</param>
  66.    ''' <returns>AgrupationCharsInfo.</returns>
  67.    ''' <exception cref="System.Exception">'InputString' parameter cannot be an empty String..</exception>
  68.    Public Function CountAgrupationsInString(ByVal AgrupationChars As Tuple(Of Char, Char),
  69.                                             ByVal InputString As String) As AgrupationCharsInfo
  70.  
  71.        If String.IsNullOrEmpty(InputString) OrElse String.IsNullOrWhiteSpace(InputString) Then
  72.            Throw New Exception("'InputString' parameter cannot be an empty String.")
  73.        End If
  74.  
  75.        Dim CharStack As New Stack(Of Integer)
  76.        Dim Result As New AgrupationCharsInfo
  77.  
  78.        With Result
  79.  
  80.            .InputString = InputString
  81.            .AgrupationChars = New Tuple(Of Char, Char)(AgrupationChars.Item1, AgrupationChars.Item2)
  82.  
  83.            For i As Integer = 0 To InputString.Length - 1
  84.  
  85.                Select Case InputString(i)
  86.  
  87.                    Case .AgrupationChars.Item1
  88.                        CharStack.Push(i)
  89.                        .OpenedAgrupationsIndex.Add(i)
  90.                        .CountOpenedAgrupations += 1
  91.  
  92.                    Case .AgrupationChars.Item2
  93.                        Select Case CharStack.Count
  94.  
  95.                            Case Is = 0
  96.                                .CountOpenedAgrupations += 1
  97.                                .OpenedAgrupationsIndex.Add(i)
  98.  
  99.                            Case Else
  100.                                .CountClosedAgrupations += 1
  101.                                .CountOpenedAgrupations -= 1
  102.                                .ClosedAgrupationsIndex.Add(Tuple.Create(Of Integer, Integer)(CharStack.Pop, i))
  103.                                .OpenedAgrupationsIndex.RemoveAt(.OpenedAgrupationsIndex.Count - 1)
  104.  
  105.                        End Select '/ CharStack.Count
  106.  
  107.                End Select '/ InputString(i)
  108.  
  109.            Next i
  110.  
  111.            .StringHasClosedAgrupations = .CountClosedAgrupations <> 0
  112.            .StringHasOpenedAgrupations = .CountOpenedAgrupations <> 0
  113.  
  114.        End With '/ Result
  115.  
  116.        Return Result
  117.  
  118.    End Function
  119.  
  120.    ''' <summary>
  121.    ''' Stores info about closed and opened agrupations of chars in a String.
  122.    ''' </summary>
  123.    Public NotInheritable Class AgrupationCharsInfo
  124.  
  125.        ''' <summary>
  126.        ''' Indicates the input string.
  127.        ''' </summary>
  128.        ''' <value>The input string.</value>
  129.        Public Property InputString As String = String.Empty
  130.  
  131.        ''' <summary>
  132.        ''' Indicates the agrupation characters.
  133.        ''' </summary>
  134.        ''' <value>The agrupation characters.</value>
  135.        Public Property AgrupationChars As Tuple(Of Char, Char) = Nothing
  136.  
  137.        ''' <summary>
  138.        ''' Determines whether the input string contains closed agrupation.
  139.        ''' </summary>
  140.        Public Property StringHasClosedAgrupations As Boolean = False
  141.  
  142.        ''' <summary>
  143.        ''' Determines whether the input string contains opened agrupations.
  144.        ''' </summary>
  145.        Public Property StringHasOpenedAgrupations As Boolean = False
  146.  
  147.        ''' <summary>
  148.        ''' Indicates the total amount of closed agrupations.
  149.        ''' </summary>
  150.        ''' <value>The closed agrupations count.</value>
  151.        Public Property CountClosedAgrupations As Integer = 0
  152.  
  153.        ''' <summary>
  154.        ''' Indicates the total amount of opened agrupations.
  155.        ''' </summary>
  156.        ''' <value>The opened agrupations count.</value>
  157.        Public Property CountOpenedAgrupations As Integer = 0
  158.  
  159.        ''' <summary>
  160.        ''' Indicates the closed agrupations index positions in the string.
  161.        ''' </summary>
  162.        ''' <value>The closed agrupations index positions.</value>
  163.        Public Property ClosedAgrupationsIndex As New List(Of Tuple(Of Integer, Integer))
  164.  
  165.        ''' <summary>
  166.        ''' Indicates the opened agrupations index positions in the string.
  167.        ''' </summary>
  168.        ''' <value>The opened agrupations index positions.</value>
  169.        Public Property OpenedAgrupationsIndex As New List(Of Integer)
  170.  
  171.    End Class '/ AgrupationCharsInfo
  172.  


« Última modificación: 28 Junio 2014, 08:36 am por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines