easy
0 views

Username Domain Extension

Parse an email address and print the extension, domain, and username in reverse order

Understand the Problem

Problem Statement

Given a string S which is of the format USERNAME@DOMAIN.EXTENSION, the program must print the EXTENSION, DOMAIN, USERNAME in the reverse order.

Constraints

  • 1 ≤ Length of S ≤ 100
  • The input string must contain exactly one '@' symbol
  • The input string must contain exactly one '.' after the '@' symbol
  • USERNAME, DOMAIN, and EXTENSION are non-empty strings

Examples

Example 1
Input
abcd@gmail.com
Output
com
gmail
abcd
Explanation

The input 'abcd@gmail.com' has USERNAME='abcd', DOMAIN='gmail', and EXTENSION='com'. The output prints them in reverse order: extension first, then domain, then username.

Solution

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char email[101];
    scanf("%s", email);
    
    // Find positions of '@' and '.'
    char *at_pos = strchr(email, '@');
    char *dot_pos = strrchr(email, '.');
    
    // Extract parts
    char username[50], domain[50], extension[50];
    
    // Username: from start to '@'
    int i = 0;
    while (email[i] != '@') {
        username[i] = email[i];
        i++;
    }
    username[i] = '\0';
    
    // Domain: from after '@' to '.'
    i = 0;
    at_pos++;
    while (at_pos != dot_pos) {
        domain[i] = *at_pos;
        i++;
        at_pos++;
    }
    domain[i] = '\0';
    
    // Extension: from after '.' to end
    i = 0;
    dot_pos++;
    while (*dot_pos != '\0') {
        extension[i] = *dot_pos;
        i++;
        dot_pos++;
    }
    extension[i] = '\0';
    
    // Print in reverse order
    printf("%s\n%s\n%s\n", extension, domain, username);
    
    return 0;
}
Time:O(n) where n is the length of the email string
Space:O(n) for storing the input string and extracted parts
Approach:

1. The C solution reads the email string using scanf
2. Uses strchr to find the '@' position and strrchr to find the last '.' position
3. Manually extracts each part by copying characters between positions
4. Uses null terminators to create proper C strings
5. Prints the three parts in reverse order using printf

Visual Explanation

Loading diagram...