javastring

Taking first uppercase character of a multiple splitted string


So I want to print out the first uppercase character when splitting my String when it reaches a special character.

public static void main(String args[]){
    Scanner sc = new Scanner(System.in);
    String input = sc.nextLine();
    if(input.contains("-")){
        for (int i = 0; i < input.length(); i++){
            String[] parts = input.split("-",2);
            String string1 = parts[0];
            String string2 = parts[1];
            System.out.print(string1.substring(0, 0) + string2.substring(0,0));
            
        }
    }
}

I'll give an example of what I'd like it to do.

> input: Please-WooRk-siR
> output: PW
> input: This-Is-A-Test
> output: TIAT

So only print the first uppercase character of each substring.


Solution

  • This is one way to do it.

          String str = "This-Is-a-Test-of-The-Problem";
          StringBuilder sb = new StringBuilder();
          for (String s : str.split("-")) {
             char c = s.charAt(0);
             if (Character.isUpperCase(c)) {
                sb.append(c);
             }
          }
          System.out.println(sb.toString());