Forum Discussion

anhvu's avatar
anhvu
Frequent Contributor
7 years ago

How to count repeated strings in a line?

Hello,

 

Could you someone show me how to count repeated string in a line?

 

 string a = "Hello how are you Hello, Hello, Hello. Hello"

 

I would like to count how many "Hello" in the  string.

 

I tried to use aqString["Find"](a,"Hello");

 

but it just found the 1st one only.

3 Replies

  • NisHera's avatar
    NisHera
    Valued Contributor

    wrote a function in JScript as follows

    function abcd(){
    var stringA = "Hello how are you Hello, Hlleo, Hello, Hello. Hello";
    var HelloCount =0;
    var startingAt =0;
    
      do {
          startingAt = aqString.Find(stringA, 'Hello', startingAt, false)+1;
          HelloCount = HelloCount+1;  }
      while (startingAt<=aqString.FindLast(stringA, 'Hello', false));
    
    Log.Message(HelloCount);
    }
    • anhvu's avatar
      anhvu
      Frequent Contributor

      I got the solution.

       

      However, thank you very much.

  • HKosova's avatar
    HKosova
    SmartBear Alumni (Retired)

    Here's another solution using a regular expression:

    var str = "Hello how are you Hello, Hello, Hello. Hello";
    var regexp = /Hello/g;
    var count = 0;
    
    var matches = str.match(regexp);
    if (matches != null)
      count = matches.length;
    
    Log.Message(count);  // 5