Home > Net >  How to iterate through a String and stop when it finds a uppercase letter
How to iterate through a String and stop when it finds a uppercase letter

Time:09-20

How to iterate through a String and stop when it finds an uppercase letter, and create two variables, one with the first part before the uppercase letter and the other variable with the second part starting with the second uppercase letter.

My code only is to detect uppercase letter.

for (int i = 0; i < phrase.length(); i  ) {
    if (Character.isUpperCase(phrase.charAt(i))) {

    }
}

CodePudding user response:

Don't know if you need to use a FOR, but I would suggest a WHILE.

index = 0;
while (!Character.isUpperCase(sixPointOneSubsectionGeneric.charAt(index))) { index  ; }

firstPart = sixPointOneSubsectionGeneric.substr(0,index);  // cut from beginning to index - 1
secondPart = sixPointOneSubsectionGeneric.substr(index); // cut from index to end

CodePudding user response:

public static void main(String[] args) {
        
        var text = "hello World";
        Integer index = null;
        for(var i = 0; i < text.length(); i  ) {
            var isUpperCase = Character.isUpperCase(text.charAt(i));
            if(isUpperCase) {
                index = i;
                break;
            }
        }
        if(index != null) {
            var firstPart = text.substring(0, index);
            var secondPart = text.substring(index);

            System.out.println(firstPart);
            System.out.println(secondPart);
        }else{
            System.out.println("No uppercase found");
            System.out.println(text);
        }
    }
  •  Tags:  
  • java
  • Related