Print String Till Character In Python
Print a substring from the beginning of a given string until a specified character is encountered.
Understand the Problem
Problem Statement
Given a string S and a character C, print the substring of S from the beginning until the character C is encountered (excluding C itself). If C is not found in S, print the entire string S.
Constraints
- Length of S is from 3 to 100 characters
- String S contains only alphabetic characters
- Character C is a single alphabetic character
- Case-sensitive matching (e.g., 'E' and 'e' are different)
Examples
manager
emanagStarting from the beginning of 'manager', we print characters until we encounter 'e' (at position 5). The characters before 'e' are 'manag'.
Everest
eEvStarting from the beginning of 'Everest', we print characters until we encounter lowercase 'e' (at position 2). The uppercase 'E' at the beginning is different from lowercase 'e', so we continue until we find the lowercase 'e'. The characters before the lowercase 'e' are 'Ev'.
hello
zhelloThe character 'z' is not found in 'hello', so we print the entire string 'hello' as the output.
Solution
#include <stdio.h>
#include <string.h>
int main() {
char S[101]; // Length constraint: 3 to 100
char C;
// Read input
fgets(S, sizeof(S), stdin);
// Remove newline if present
int len = strlen(S);
if (S[len-1] == '\n') {
S[len-1] = '\0';
}
scanf("%c", &C);
// Print characters until C is encountered
int i = 0;
while (S[i] != '\0' && S[i] != C) {
printf("%c", S[i]);
i++;
}
printf("\n");
return 0;
}C Solution Logic:
1. Declare a character array S with size 101 (to accommodate strings up to 100 characters plus null terminator)
2. Read the string S using fgets() to handle spaces if any
3. Remove trailing newline character from fgets
4. Read the target character C using scanf
5. Iterate through the string character by character using a while loop
6. Print each character until either the end of string ('\0') or the target character C is encountered
7. Print a newline after the result
Key Points:
- Uses manual iteration for character-by-character processing
- Handles the case where C is not found (loop continues until end of string)
- Case-sensitive comparison (standard behavior)