Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
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
Up Next
C# Code to Find Count of Sub-string Occurrences