Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Searching & Counting Occurrences | Fundamentals of Strings
C# Strings & Text Processing

bookSearching & Counting Occurrences

When working with text, you often need to find out whether a certain character or word appears within a string, or how many times it occurs. This is a common task in many real-world scenarios, such as checking how often a letter appears in a paragraph, counting specific keywords in documents, or searching for patterns in user input. Being able to search and count occurrences gives you essential tools for text analysis and validation.

Program.cs

Program.cs

copy
1234567891011121314151617181920212223
namespace ConsoleApp { public class Program { public static void Main(string[] args) { string sentence = "Programming in C# is fun!"; char target = 'g'; int count = 0; for (int i = 0; i < sentence.Length; i++) { if (sentence[i] == target) { count++; } } System.Console.WriteLine($"The character '{target}' appears {count} times."); } } }

In this example, you use a loop to examine each character in the sentence. The loop starts at the first character and goes through to the last, checking one character at a time. For each character, you compare it to the target character using the equality operator (==). If the character matches the target, you increase the count variable by one. After the loop finishes, count holds the total number of times the character appeared in the sentence.

Program.cs

Program.cs

copy
12345678910111213141516171819202122
namespace ConsoleApp { public class Program { public static void Main(string[] args) { string text = "The theme of the event is 'Theatre'."; string search = "the"; int count = 0; int index = 0; while ((index = text.IndexOf(search, index)) != -1) { count++; index += search.Length; } System.Console.WriteLine($"The substring \"{search}\" appears {count} times."); } } }

When searching for substrings, you can use the IndexOf method to find the position of the substring within the text. By starting your search from the last found position plus the length of the substring, you avoid counting overlapping occurrences or getting stuck in an infinite loop. This approach is case-sensitive, so searching for "the" will not match "The" unless you adjust the case of the text or the search term. If you want to perform a case-insensitive search, you can convert both the text and the search term to the same case using ToLower() or ToUpper() before searching, or use overloads of IndexOf that accept a StringComparison parameter.

Note
Study More

The StringComparison enumeration in C# allows you to specify different ways to compare strings, such as OrdinalIgnoreCase for case-insensitive searches or CurrentCulture for culture-aware comparisons. Explore the documentation on StringComparison to learn more about advanced searching options.

12345678
// General pattern for counting substring occurrences int count = 0; int index = 0; while ((index = text.IndexOf(substring, index)) != -1) { count++; index += substring.Length; }
copy

1. What is the main purpose of using a loop when counting characters in a string?

2. Which method can be used to find the position of a substring?

3. How can you make a search case-insensitive?

question mark

What is the main purpose of using a loop when counting characters in a string?

Select the correct answer

question mark

Which method can be used to find the position of a substring?

Select the correct answer

question mark

How can you make a search case-insensitive?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 5

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Suggested prompts:

Can you explain how the IndexOf method works in more detail?

How can I modify this code to perform a case-insensitive search?

What should I do if I want to count overlapping occurrences of a substring?

bookSearching & Counting Occurrences

Deslize para mostrar o menu

When working with text, you often need to find out whether a certain character or word appears within a string, or how many times it occurs. This is a common task in many real-world scenarios, such as checking how often a letter appears in a paragraph, counting specific keywords in documents, or searching for patterns in user input. Being able to search and count occurrences gives you essential tools for text analysis and validation.

Program.cs

Program.cs

copy
1234567891011121314151617181920212223
namespace ConsoleApp { public class Program { public static void Main(string[] args) { string sentence = "Programming in C# is fun!"; char target = 'g'; int count = 0; for (int i = 0; i < sentence.Length; i++) { if (sentence[i] == target) { count++; } } System.Console.WriteLine($"The character '{target}' appears {count} times."); } } }

In this example, you use a loop to examine each character in the sentence. The loop starts at the first character and goes through to the last, checking one character at a time. For each character, you compare it to the target character using the equality operator (==). If the character matches the target, you increase the count variable by one. After the loop finishes, count holds the total number of times the character appeared in the sentence.

Program.cs

Program.cs

copy
12345678910111213141516171819202122
namespace ConsoleApp { public class Program { public static void Main(string[] args) { string text = "The theme of the event is 'Theatre'."; string search = "the"; int count = 0; int index = 0; while ((index = text.IndexOf(search, index)) != -1) { count++; index += search.Length; } System.Console.WriteLine($"The substring \"{search}\" appears {count} times."); } } }

When searching for substrings, you can use the IndexOf method to find the position of the substring within the text. By starting your search from the last found position plus the length of the substring, you avoid counting overlapping occurrences or getting stuck in an infinite loop. This approach is case-sensitive, so searching for "the" will not match "The" unless you adjust the case of the text or the search term. If you want to perform a case-insensitive search, you can convert both the text and the search term to the same case using ToLower() or ToUpper() before searching, or use overloads of IndexOf that accept a StringComparison parameter.

Note
Study More

The StringComparison enumeration in C# allows you to specify different ways to compare strings, such as OrdinalIgnoreCase for case-insensitive searches or CurrentCulture for culture-aware comparisons. Explore the documentation on StringComparison to learn more about advanced searching options.

12345678
// General pattern for counting substring occurrences int count = 0; int index = 0; while ((index = text.IndexOf(substring, index)) != -1) { count++; index += substring.Length; }
copy

1. What is the main purpose of using a loop when counting characters in a string?

2. Which method can be used to find the position of a substring?

3. How can you make a search case-insensitive?

question mark

What is the main purpose of using a loop when counting characters in a string?

Select the correct answer

question mark

Which method can be used to find the position of a substring?

Select the correct answer

question mark

How can you make a search case-insensitive?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 5
some-alt