xtool
xtool

Reputation: 31

How to check how many times a string exist in another string

I Want to see how many time's a string occurrs in a string. For example I want to see how many times 2018 occurs in this paragraph:

zaeazeaze2018 azeazeazeazeaze2018azezaaze azeaze4azeaze2018

In this case it is occuring 3 times.

I tried the following code

But the problem is that it always returns 0

And I can't find the mistake here:

public static string count(string k)
{
    int i = 0;
    foreach(var  line in k)
    {
        if (line.ToString().Contains("Bestellung sehen"))
        {
            i++;
            i = +i;
        }

    }
    return i.ToString();
}

Upvotes: 0

Views: 722

Answers (4)

Jack Casey
Jack Casey

Reputation: 1836

This can be accomplished using Regular Expressions with the following:

using System.Text.RegularExpressions;

public static int count(string fullString, string searchPattern)
{
    int i = Regex.Matches(fullString, searchPattern).Count;
    return i;
}

For example, the following returns 2 as an int, not string:

count("asdfasdfasfdfindmeasdfadfasdasdfasdffindmesadf","findme")

I find this is quick enough for most of my use cases.

Upvotes: 1

Rahul Sharma
Rahul Sharma

Reputation: 8302

You can use Regular Expressions to handle such cases. Regular expressions give you good flexibility over your pattern matching in a string. In your case, I have prepared a sample code for you using Regular Expressions:

using System;
using System.Text.RegularExpressions;
                
public class Program
{
    public static void Main()
    {
        string str="zaeazeaze2018azeazeazeazeaze2018azezaazeazeaze4azeaze2018";
        string regexPattern = @"2018";
        int numberOfOccurence = Regex.Matches(str, regexPattern).Count;
        
        Console.WriteLine(numberOfOccurence);
        
    }
}

Working example: https://dotnetfiddle.net/PGgbm8

If you will notice the line string regexPattern = @"2018";, this sets the pattern to find all occurences of 2018 from your string. You can change this pattern according to what you require. A simple example would be that if I changed the pattern to string regexPattern = @"\d+";, it would give me 4 as output. This is because my pattern will match all occurences of numbers in the string.

Upvotes: 1

miss nefrat
miss nefrat

Reputation: 103

use this :

string text = "Hello2018,world2018\r\nWe have five 2018 here\r\n2018is coming2018"
int Counter = Regex.Matches(text, "2018").Count;
Console.WriteLine(Counter.ToString()); //write : 5

Upvotes: 1

Sean
Sean

Reputation: 51

str is your String from your count method str2 is your substring which is Bestellung sehen

int n = str2.length
int k = 0;
for(int i=0;i < str.length; i++){
    if(str.substring(i,i+n-1)){
        k++;
        if(i+n-1 >= str.length){
            break;
        }
    }
}

return k.toString()

Upvotes: -1

Related Questions