如何统计字符串中连续出现超2次的下划线占位符出现次数
Got it, let's revamp your original code to meet the new requirement: counting only placeholder sequences where 3 or more consecutive underscores appear (single or double underscores don't count as valid placeholders).
Approach 1: Iterative Counting (Explicit Loop)
This method gives you full control over the counting logic, which is great for clarity if you need to adjust rules later. Here's the modified code with comments:
void Main() { string someString = "Fill ________ and ______ this"; char targetChar = '_'; int validPlaceholderCount = 0; int currentConsecutiveCount = 0; // Iterate through each character in the string foreach (char c in someString) { if (c == targetChar) { // Increment counter when we hit an underscore currentConsecutiveCount++; } else { // Check if we just finished a valid placeholder (3+ underscores) if (currentConsecutiveCount > 2) { validPlaceholderCount++; } // Reset the counter for the next potential sequence currentConsecutiveCount = 0; } } // Don't forget to check the last sequence if the string ends with underscores! if (currentConsecutiveCount > 2) { validPlaceholderCount++; } Console.WriteLine($"Valid placeholders found: {validPlaceholderCount}"); // Output for your example string: 2 }
Key notes for this approach:
- We track
currentConsecutiveCountto keep tabs on how many underscores we've seen in a row. - When we hit a non-underscore character, we check if the previous sequence was long enough to be a valid placeholder.
- We add a final check after the loop to catch cases where the string ends with a valid placeholder sequence.
Approach 2: Regular Expressions (Shorter Code)
If you prefer a more concise solution, regular expressions are perfect here. We can match all sequences of 3 or more underscores in one go:
using System.Text.RegularExpressions; void Main() { string someString = "Fill ________ and ______ this"; // Regex pattern: match 3 or more consecutive underscores MatchCollection placeholderMatches = Regex.Matches(someString, @"_{3,}"); // The number of matches is our valid placeholder count int validPlaceholderCount = placeholderMatches.Count; Console.WriteLine($"Valid placeholders found: {validPlaceholderCount}"); // Also outputs 2 for your example }
This method is great for simple pattern matching—less code to write and read. The @{3,} pattern means "match the underscore character 3 or more times consecutively".
Test Cases to Verify
- Input:
"Single _ here"→ Output:0(only one underscore) - Input:
"Two __ separate __ underscores"→ Output:0(two sequences of two underscores each) - Input:
"Your example: Fill ________ and ______ this"→ Output:2(two sequences of 8 and 6 underscores)
内容的提问来源于stack exchange,提问作者Nody

