Skip to main content

Write a method to move hyphens to the left and characters to the right in a string

 Ex:-     code--heist--   ==>     ----codeheist

Note:-  Return null or None if str is empty.

Java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
 public static String moveHyphens(String str) 
 {
    if(str.length()==0)
        return null;
    else{
        String result = "";
        for(int i=0; i<str.length(); i++){
            char ch = str.charAt(i);
            if(ch=='-')
                result = ch + result;
            else
                result += ch;
        }
        return result;
    }
 }

Python

def moveHyphens(str):
    if len(str)==0:
        return None
    else:
        result = ""
        for char in str:
            if char=='-':
                result = char + result;
            else:
                result += char
        return result