C # Count The number and position of N identical substrings

Source: Internet
Author: User

 

Using System. Text. RegularExpressions;

/// <Summary>

/// Calculate the number of times a substring appears.

/// </Summary>

/// <Param name = "str"> string </param>

/// <Param name = "substring"> substring </param>

/// <Returns> Number of occurrences </returns>

Public static int SubstringCount (string str, string substring)

{

If (str. Contains (substring ))

{

String strReplaced = str. Replace (substring ,"");

Return (str. Length-strReplaced. Length)/substring. Length;

}

 

Return 0;

}

// Call example. Here is only a reference.

Private void FindPosition ()

{

STemp = "aabbccdd \ r \ naa3323 \ r \ naa325sdf \ r \ n233asdf554 \ r \ n"; // here is the original string

Int iCount = SubstringCount (sTemp, "\ r \ n"); // here \ r \ n is the delimiter

If (iCount> 3)

{

Regex reg = new Regex ("\ r \ n ");

Match mat = reg. Match (sTemp );

Int iCountTemp = 0;

While (mat. Success)

{

ICountTemp ++;

// MessageBox. Show (mat. Index. ToString (); // location

If (iCountTemp> 20)

{

STemp = sTemp. Substring (0, mat. Index );

Break;

}

Mat = reg. Match (sTemp, mat. Index + mat. Length );

}

}

}

 

From the column keenweiwei

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.