Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print the string after the specified character has occurred given no. of times in C Program
In C programming, we often need to extract a substring after a specific character has occurred a certain number of times. This task involves scanning through a string and printing all characters after the nth occurrence of a specified character.
Syntax
for (i = 0; i < string_length; i++) {
if (count > 0) {
if (string[i] == target_char) {
count--;
}
continue;
}
printf("%c", string[i]);
}
Algorithm
START
Step 1 ? Input character (e.g. 'a') and count (e.g. 2)
Step 2 ? Declare string and calculate its length
Step 3 ? Loop through each character in the string
IF count > 0
IF current character matches target character
Decrement count
End IF
Continue to next character
End IF
ELSE
Print current character
End ELSE
Step 4 ? End Loop
STOP
Example
The following program prints the string after the character 'a' has occurred 2 times −
#include <stdio.h>
#include <string.h>
int main() {
char string[] = "I am Harsh Vaid";
char ch = 'a';
int count = 2;
int n = strlen(string);
printf("Original string: %s<br>", string);
printf("Character to find: '%c'<br>", ch);
printf("Occurrence count: %d<br>", count);
printf("Result: ");
for(int i = 0; i < n; i++) {
if(count > 0) {
if(string[i] == ch) {
count--;
}
continue;
}
printf("%c", string[i]);
}
printf("<br>");
return 0;
}
Original string: I am Harsh Vaid Character to find: 'a' Occurrence count: 2 Result: rsh Vaid
How It Works
- The program iterates through each character of the string
- When
count > 0, it looks for the target character and decrements the counter - Once the specified number of occurrences are found (
count = 0), it starts printing the remaining characters - The
continuestatement skips printing until the target occurrences are reached
Key Points
- Use
strlen()instead ofsizeof()for proper string length calculation - The algorithm has O(n) time complexity where n is the string length
- If the character doesn't occur the specified number of times, nothing is printed
Conclusion
This approach efficiently extracts substring after nth occurrence of a character using a simple counter mechanism. The method is straightforward and handles edge cases where the character may not appear enough times.
Advertisements
