-1

I'm unsure of the code for this, but if one were to input "oooooooooo" after a prompt (like in an if-statement or something where the program registers "o" as "one" or something), how could you make "oooooooooo" translate into "o"?

Would one have to write down manually various iterations of "o" (like, "oo" and "ooo" and "oooo"...etc.). Would it be similar to something like the ignore case method where O and o become the same? So "ooo..." and "o" end up as the same string.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • 1
    I think you're looking for [`String#replaceAll()`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceAll-java.lang.String-java.lang.String-). If you aren't familiar with regular expressions, [Learning Regular Expressions](https://stackoverflow.com/questions/4736/learning-regular-expressions) is a good place to start. – azurefrog Oct 20 '17 at 21:26
  • 1
    You could use a regex and match `o+`, meaning "o" repeated 1 or more times – Blorgbeard Oct 20 '17 at 21:32
  • Where is your attempt? –  Oct 21 '17 at 07:15

4 Answers4

0

using regex:

public static String getSingleCharacter(String input){
       if(input == null || input.length() == 0) return null;
       if(input.length() == 1) return input;
       if(!input.toLowerCase().matches("^\\w*?(\\w)(?!\\1|$)\\w*$")){
           return Character.toString(input.toLowerCase().charAt(0));
       }
       return null;
}

if the method returns null then the characters are not all the same, else it will return that single char represented as a string.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

Although probably overkill for this one use-case, it would be helpful to learn how to use regexes in the future. Java provides a regex library to use called Pattern. For example, the regex /o+ne/ would match any string "o...ne" with at least one "o".

PJ K
  • 74
  • 1
  • 4
0

Use the regular expression /(.)\1+/ and String#replaceAll() to match runs of two or more of the same character and then replace the match with the value of the first match group identified with $1 as follows:

public static String squeeze(String input) {
    return input.replaceAll("(.)\\1+", "$1");
}

String result = squeeze("aaaaa bbbbbbb cc    d"); 

assert(result.equals("a b c d"));
Lachlan Dowding
  • 4,356
  • 1
  • 15
  • 18
-1
public string condense(String input) {
    if(input.length >= 3) {
        for(int i=0; i< input.length-2; i++){
            if(input.substring(i,i+1) != input.substring(i+1,i+2)){
                return input;
            }
        }
    }
    return input.substring(0,1);
}

This checks if the string is 3 characters or longer, and if so it loops through the entire string. If every character in the string is the same, then it returns a condensed version of the string.