C# Corner
Tech
News
Videos
Forums
Trainings
Books
Events
More
Interviews
Jobs
Live
Learn
Career
Members
Blogs
Challenges
Certifications
Bounties
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
C# Code to Find Count of Sub-string Occurrences
WhatsApp
Kannadasan G
Mar 29
2016
1.3
k
0
0
Using IndexOf:
string
MyString =
"OU=Level3,OU=Level2,OU=Level1,DC=domain,DC=com"
;
string
stringToFind =
"OU="
;
List<
int
> positions =
new
List<
int
>[];
int
pos = 0;
while
((pos < MyString.Length) && (pos = MyString.IndexOf(stringToFind, pos)) != -1)
{
positions.Add(pos);
pos += stringToFind.Length();
}
Console.WriteLine(
"{0} occurrences"
, positions.Count);
foreach
(var p
in
positions)
{
Console.WriteLine(p);
}
Using Regex:
var matches = Regex.Matches(MyString,
"OU="
);
Console.WriteLine(
"{0} occurrences"
, matches.Count);
foreach
(var m
in
matches)
{
Console.WriteLine(m.Index);
}
Count of Sub-string Occurrences
C#.net