Reverse String Till Underscore - Spicy Coders

Tuesday, October 03, 2017

Reverse String Till Underscore

download+%25282%2529
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. blogger_logo_round_35

    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. blogger_logo_round_35

      bro can tell the code using try except block

      Delete
  2. blogger_logo_round_35

    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. blogger_logo_round_35

    Sub string is not passesd as the input

    ReplyDelete
  4. blogger_logo_round_35

    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. blogger_logo_round_35

    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