easy
0 views

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

Example 1
Input
manager
e
Output
manag
Explanation

Starting from the beginning of 'manager', we print characters until we encounter 'e' (at position 5). The characters before 'e' are 'manag'.

Example 2
Input
Everest
e
Output
Ev
Explanation

Starting 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'.

Example 3
Input
hello
z
Output
hello
Explanation

The 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;
}
Time:O(n) where n is the length of the string
Space:O(1) additional space (not counting input storage)
Approach:

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)

Visual Explanation

Loading diagram...