TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
C# Code to Find Count of Sub-string Occurrences
Kannadasan G
Mar 29
2016
Code
1.2
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
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