sourcecode

문자열에서 발생한 특정 문자 수

copyscript 2023. 5. 14. 10:57
반응형

문자열에서 발생한 특정 문자 수

문자열에서 특정 문자의 발생 횟수를 계산하는 가장 간단한 방법은 무엇입니까?

즉, 함수를 작성해야 합니다, 카운트.캐릭터들(), 그래서.

str = "the little red hen"
count = countTheCharacters(str,"e") ' Count should equal 4
count = countTheCharacters(str,"t") ' Count should equal 3

가장 간단한 방법은 문자열의 문자를 반복하는 것입니다.

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Dim cnt As Integer = 0
  For Each c As Char In value
    If c = ch Then 
      cnt += 1
    End If
  Next
  Return cnt
End Function

용도:

count = CountCharacter(str, "e"C)

거의 효과적이고 더 짧은 코드를 제공하는 또 다른 접근 방식은 LINQ 확장 방법을 사용하는 것입니다.

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Return value.Count(Function(c As Char) c = ch)
End Function

간단한 방법은 다음과 같습니다.

text = "the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3

해보세요.

Dim occurCount As Integer = Len(testStr) - Len(testStr.Replace(testCharStr, ""))

여기 간단한 버전이 있습니다.

text.count(function(x) x = "a")

위의 내용은 문자열에 있는 a의 번호를 제공합니다.사례를 무시하려는 경우:

text.count(function(x) Ucase(x) = "A")

아니면 글자만 세고 싶으시면:

text.count(function(x) Char.IsLetter(x) = True)

한번 해보세요!

고마워, @guffa.한 줄로 또는 의 더 긴 문 내에서 수행할 수 있는 기능.NET은 매우 편리합니다.이 VB.NET 예제는 라인피드 문자 수를 계산합니다.

Dim j As Integer = MyString.Count(Function(c As Char) c = vbLf)

j는 MyString의 LineFeed 수를 반환합니다.

또는 (VB 단위).NET):

Function InstanceCount(ByVal StringToSearch As String,
                       ByVal StringToFind As String) As Long
    If Len(StringToFind) Then
        InstanceCount = UBound(Split(StringToSearch, StringToFind))
    End If
End Function

우즈왈 마난드하르의 코드를 VB로 변환합니다.다음과 같은 NET...

Dim a As String = "this is test"
Dim pattern As String = "t"
Dim ex As New System.Text.RegularExpressions.Regex(pattern)
Dim m As System.Text.RegularExpressions.MatchCollection
m = ex.Matches(a)
MsgBox(m.Count.ToString())

이것이 가장 쉬울 것 같습니다.

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Return len(value) - len(replace(value, ch, ""))
End Function
Public Class VOWELS

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim str1, s, c As String
        Dim i, l As Integer
        str1 = TextBox1.Text
        l = Len(str1)
        c = 0
        i = 0
        Dim intloopIndex As Integer
        For intloopIndex = 1 To l
            s = Mid(str1, intloopIndex, 1)
            If (s = "A" Or s = "a" Or s = "E" Or s = "e" Or s = "I" Or s = "i" Or s = "O" Or s = "o" Or s = "U" Or s = "u") Then
                c = c + 1
            End If
        Next
        MsgBox("No of Vowels: " + c.ToString)
    End Sub
End Class

이 솔루션을 발견했을 때 세고 싶은 문자열이 한 문자보다 길기 때문에 약간 다른 것을 찾고 있었기 때문에 다음 솔루션을 생각해 냈습니다.

    Public Shared Function StrCounter(str As String, CountStr As String) As Integer
        Dim Ctr As Integer = 0
        Dim Ptr As Integer = 1
        While InStr(Ptr, str, CountStr) > 0
            Ptr = InStr(Ptr, str, CountStr) + Len(CountStr)
            Ctr += 1
        End While
        Return Ctr
    End Function

정규식 사용 중...

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Return (New System.Text.RegularExpressions.Regex(ch)).Matches(value).Count
End Function
Public Function CountOccurrences(ByVal StToSerach As String, ByVal StToLookFor As String) As Int32

    Dim iPos = -1
    Dim iFound = 0
    Do
        iPos = StToSerach.IndexOf(StToLookFor, iPos + 1)
        If iPos <> -1 Then
            iFound += 1
        End If<br/>
    Loop Until iPos = -1
    Return iFound
End Function

코드 사용:

Dim iCountTimes As Integer = CountOccurrences("Can I call you now?", "a")

또한 확장으로 사용할 수도 있습니다.

<Extension()> _
Public Function CountOccurrences(ByVal StToSerach As String, ByVal StToLookFor As String) As Int32
    Dim iPos = -1
    Dim iFound = 0
    Do
        iPos = StToSerach.IndexOf(StToLookFor, iPos + 1)
        If iPos <> -1 Then
            iFound += 1
        End If
    Loop Until iPos = -1
    Return iFound
End Function

코드 사용:

Dim iCountTimes2 As Integer = "Can I call you now?".CountOccurrences("a")

다음과 같이 하는 것이 좋습니다.

String.Replace("e", "").Count
String.Replace("t", "").Count

사용할 수도 있습니다..Split("e").Count - 1또는.Split("t").Count - 1각각, 하지만 예를 들어, 당신이 e 또는 at를 시작할 때 잘못된 값을 제공합니다.String.

eCount = str.Length - Replace(str, "e", "").Length
tCount = str.Length - Replace(str, "t", "").Length

또 다른 방법은 스플릿으로 작업하는 것입니다.

Dim tmp() As String
tmp = Split(Expression, Delimiter)
Dim count As Integer = tmp.Length - 1

저는 LINQ를 사용하고 있으며 솔루션은 매우 간단합니다.

C#의 코드:

count = yourString.ToCharArray().Count(c => c == 'e');

함수의 코드:

public static int countTheCharacters(string str, char charToCount){
   return str.ToCharArray().Count(c => c == charToCount);
}

함수 호출:

count = countTheCharacters(yourString, 'e');

그렇게 간단한 것에 대한 엄청난 암호화:

C#에서 확장 메서드를 만들고 LINQ를 사용합니다.

public static int CountOccurences(this string s, char c)
{
    return s.Count(t => t == c);
}

용도:

int count = "toto is the best".CountOccurences('t');

결과: 4.

저는 가장 좋은 답을 찾았습니다 :P :

String.ToString.Count - String.ToString.Replace("e", "").Count
String.ToString.Count - String.ToString.Replace("t", "").Count

var charCount = "string with periods...".Count(x => '.' == x);

저는 다음과 같은 기능을 사용합니다.가장 메모리 효율적이지는 않지만 이해하기가 매우 간단하고, 여러 비교 방법을 지원하며, 4줄에 불과하며, 속도가 빠르고, 대부분 VBA에서도 작동하며, 개별 문자뿐만 아니라 검색 문자열도 찾을 수 있습니다(나는 종종 VbCrLf(s)).

유일하게 누락된 것은 다른 "시작"에서 검색을 시작하는 기능입니다.

    Function inStC(myInput As String, Search As String, Optional myCompareMethod As Long = CompareMethod.Text) As Long
        If InStr(1, myInput, Search, myCompareMethod) = 0 Then Return 0
        Return UBound(Split(myInput, Search,, myCompareMethod))
    End Function

제가 좋아하는 한 가지는 예시를 사용하기에 컴팩트하다는 것입니다.

str="the little red hen"
count=inStC(str,"e") 'count should equal 4
count=inStC(str,"t") 'count should equal 3

여기 있는 동안 문자열 카운트를 반환하는 대신 검색 문자열이 있는 경우 부울을 반환하는 inStB 함수를 실드하고 싶습니다.나는 이 기능이 자주 필요하고 이것은 내 코드를 더 깨끗하게 만듭니다.

Function inStB(myInput As String, Search As String, Optional Start As Long = 1, Optional myCompareMethod As Long = CompareMethod.Text) As Boolean
    If InStr(Start, myInput, Search, myCompareMethod) > 0 Then Return True
    Return False
End Function

또 다른 가능성은 정규식을 사용하는 것입니다.

string a = "this is test";
string pattern = "t";
System.Text.RegularExpressions.Regex ex = new System.Text.RegularExpressions.Regex(pattern);
System.Text.RegularExpressions.MatchCollection m = ex.Matches(a);
MessageBox.Show(m.Count.ToString());

이것을 VB로 변환해 주세요.그물.

사용:

Function fNbrStrInStr(strin As Variant, strToCount As String)
    fNbrStrInStr = UBound(Split(strin, strToCount)) - LBound(Split(strin, strToCount))
End Function

저는 용한사를 요.strin매우 긴 텍스트를 처리하기 위한 변형입니다.분할은 사용자 설정에 따라 0 기반 또는 1 기반일 수 있으며, 이를 빼면 정확한 카운트가 보장됩니다.

다음보다 긴 strcount에 대한 테스트를 포함하지 않았습니다.strin코드를 간결하게 유지합니다.

    ' Trying to find the amount of "." in the text
    ' if txtName looks like "hi...hi" then intdots will = 3
    Dim test As String = txtName.Text
    Dim intdots As Integer = 0
    For i = 1 To test.Length
        Dim inta As Integer = 0 + 1
        Dim stra As String = test.Substring(inta)
        If stra = "." Then
            intdots = intdots + 1
        End If
    Next
    txttest.text = intdots
Private Sub Data_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Data.KeyPress
    If Not IsNumeric(e.KeyChar) And Not e.KeyChar = ChrW(Keys.Back) And Not e.KeyChar = "." Then
        e.Handled = True
    Else
        If e.KeyChar = "." And Data.Text.ToCharArray().Count(Function(c) c = ".") > 0 Then
            e.Handled = True
        End If
    End If
End Sub

사용:

Dim a
inputString = InputBox("Enter String", "Enter Value", "")

MyString = UCase(inputString)

MsgBox MyString

Dim stringLength

stringLength = Len(MyString)

Dim temp

output = ""

i = 1
Do
    temp = Mid(MyString, i, 1)

    MsgBox temp & i

    CharacterCount = len(MyString) - len(Replace(MyString, temp, ""))

    MyString = Replace(MyString, temp, "")

    output = output & temp & ": " & CharacterCount & vbNewline

Loop While MyString <> ""

MsgBox output

OP의 문제를 해결하는 직접 코드는 다음과 같습니다.

        Dim str As String = "the little red hen"

        Dim total As Int32

        Dim Target As String = "e"
        Dim Temp As Int32
        Dim Temp2 As Int32 = -1
Line50:
        Temp = str.IndexOf(Target, Temp2 + 1)
        Temp2 = Temp
        If Temp <> -1 Then

            ' Means there is a target there
            total = total + 1
            GoTo Line50
        End If

        MessageBox.Show(CStr(total))

이제, 이것은 OP의 문제를 해결하기 위한 편리한 기능입니다.

    Public Function CountOccurrence(ByVal YourStringToCountOccurrence As String, ByVal TargetSingleCharacterToCount As String) As Int32
        Dim total As Int32

        Dim Temp As Int32
        Dim Temp2 As Int32 = -1
Line50:
        Temp = YourStringToCountOccurrence.IndexOf(TargetSingleCharacterToCount, Temp2 + 1)
        Temp2 = Temp
        If Temp <> -1 Then

            ' Means there is a target there
            total = total + 1
            GoTo Line50
        Else
            Return total
        End If
    End Function

기능 사용 예:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim str As String = "the little red hen"

    MessageBox.Show(CStr(CountOccurrence(str, "e")))
    ' It will return 4
End Sub

언급URL : https://stackoverflow.com/questions/5193893/count-specific-character-occurrences-in-a-string

반응형