Reverse String Till Underscore - Spicy Coders

Recent

Tuesday, October 03, 2017

Reverse String Till Underscore

String S is passed as the input to the program. S may or may not have a single underscore embedded in it. The program must reverse the String S till the first underscore and print it as the output. 

Input Format: The first line contains S. 

Output Format: The first line contains the string S modified based on the given conditions. 

Boundary Conditions: Length of S is from 3 to 100. 

Example Input/Output 1: 
Input: 
abcd_pqrs 

Output: 
dcba_pqrs 

Example Input/Output 2: 
Input: 
_kilo 

Output:
_kilo 

Example Input/Output 3: 
Input:
nounderscore 

Output: 
erocsrednuon

Source Code:

import java.util.*;
public class Hello {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        String s1=s.nextLine();
        int u=s1.indexOf('_');
        if(u==-1)
        System.out.print(new StringBuffer(s1).reverse().toString());
        else if(u==0)
        System.out.print(s1);
        else
        {
           if(u==s1.length()-1)
           {
               String[] s2=s1.split("_");
               System.out.print(new StringBuilder(s2[0]).reverse().toString()+"_");
           }
           else
           {
               String[] s2=s1.split("_");
               System.out.print(new StringBuilder(s2[0]).reverse().toString()+"_"+s2[1]);
           }
        }
    }
}


Source Code: //Python

s=input()
n=s.index("_")
if n==-1:
    print(s[::-1])
elif n==len(s)-1:
    print(s[:len(s)-1]+"_")
else:

    print(s[:n][::-1]+s[n:])

6 comments:

  1. this python code has some faults

    1.it returns a value error which has to be handled using a try except block
    2.[::-1] missing in the print statement in the elif block

    Else executes just fine!

    ReplyDelete
    Replies
    1. bro can tell the code using try except block

      Delete
  2. This python code has some error which if there is no underscore in the string thn how it will take it as in -1th index

    ReplyDelete
  3. Sub string is not passesd as the input

    ReplyDelete
  4. I think this code fails to work for 3rd input ..since there is no "_" index() func will return with error.you may try it with a if and else instead. visit

    https://pythonic-solutions.blogspot.com/2020/09/reverse-string-till-special-character.html

    for solution

    ReplyDelete
  5. x=input().strip()
    t=""
    d=-1
    d=x.find('_')
    if d!=-1:
    print(x[:d][::-1],end="")
    print(x[d:])
    else:
    print(x[::-1])
    #This code will pass all test cases💯

    ReplyDelete