locked
Count same word in text file RRS feed

  • Question

  • User1109811461 posted

    Hi all expert,

    i want to count how many word in text file, example in my .txt file i got word "car" then i want to count it how many word "car" in my text file,

    below is my code which i think is not right to use.

    Dim count As Integer = 0
    For Each line As String In File.ReadLines("D:\check.txt")
    If line.Equals(IP) Then
    response.redirect("")
    count = count + 1
    End If
    Next line

    Thanks.

    Tuesday, May 22, 2018 4:37 AM

Answers

  • User-821857111 posted

    The best tool for this job is Regular Expressions:

    Dim input = File.ReadAllText("D:\check.txt")
    Dim pattern = "\bcar\b"
    Dim matches = Regex.Matches(input, pattern)
    Dim count = matches.Count

    The pattern will find car as a whole word so that it will be found in "My fast car", but not in "Sweet Caroline".

    You have a Response.Redirect in your code which means that as soon as the code finds a match, your page code will stop executing and the user will be redirected to another page. You will never be able to count all the occurrences of the string that you want to find.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 22, 2018 10:39 AM

All replies

  • User-821857111 posted

    The best tool for this job is Regular Expressions:

    Dim input = File.ReadAllText("D:\check.txt")
    Dim pattern = "\bcar\b"
    Dim matches = Regex.Matches(input, pattern)
    Dim count = matches.Count

    The pattern will find car as a whole word so that it will be found in "My fast car", but not in "Sweet Caroline".

    You have a Response.Redirect in your code which means that as soon as the code finds a match, your page code will stop executing and the user will be redirected to another page. You will never be able to count all the occurrences of the string that you want to find.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 22, 2018 10:39 AM
  • User1109811461 posted

    Hi Mike,

    its work for me the explanation make me more understand.

    Thanks a lot's.

    Monday, May 28, 2018 1:31 AM