Jay Lefler
Jay Lefler

Reputation: 315

Search for Capital Letter in String

I am trying to search a string for the last index of a capital letter. I don't mind using regular expressions, but I'm not too familiar with them.

int searchPattern = searchString.lastIndexOf(" ");      
String resultingString = searchString.substring(searchPattern + 1);

As you can see, with my current code I'm looking for the last space that is included in a string. I need to change this to search for last capital letter.

Upvotes: 4

Views: 48163

Answers (6)

kg3
kg3

Reputation: 19

LeetCode - Detect capitals

class Solution {
    public boolean detectCapitalUse(String word) {
        int len = word.length();

        if (word.charAt(0) >= 'A' && word.charAt(0) <= 'Z') {
            if (word.charAt(len-1) >= 'A' && word.charAt(len-1) <= 'Z') {
                for (int i = 1 ; i < len-1 ; i++) {
                    if ( word.charAt(i) < 'A' || word.charAt(i) > 'Z')
                        return false;
                }
            } else {
                for (int i = 1 ; i <= len-1 ; i++) {
                    if ( word.charAt(i) < 'a' || word.charAt(i) > 'z')
                        return false;
                }
            }
        } else {
            for (int i = 0 ; i <= len-1 ; i++) {
                if ( word.charAt(i) < 'a' || word.charAt(i) > 'z')
                    return false;
            }
        }
        return true;
    }
}

Upvotes: 0

Fakhar Iqbal
Fakhar Iqbal

Reputation: 4069

In Android (Java) you can use this:

String s = MyDocumentFileIsHere;
String textWithSpace = s.replaceAll("(.)([A-Z])", "$1 $2");
holder.titleTxt.setText(textWithSpace);

The result of String will be "My Document File Is Here"

Upvotes: 3

Mohammad
Mohammad

Reputation: 6148

You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem.

/**
 * Finds the last uppercase letter in a String.
 */
public class FindLastCapitalLetter {
    public static void main(String[] args) {
        String str = "saveChangesInTheEditor";
        int lastUppercaseLetter = findLastUppercaseLetter(str);
        if (lastUppercaseLetter != -1) {
            System.out.println("The last uppercase letter is "
                    + Character.toString((char) lastUppercaseLetter));
        } else {
            System.out.println("No uppercase letter was found in the String.");
        }
    }

    private static int findLastUppercaseLetter(String str) {
        return new StringBuilder(str).reverse().toString().chars()
                .filter(c -> Character.isUpperCase(c)).findFirst().orElse(-1);
    }
}

Sample output:

The last uppercase letter is E

Also, this code gives you the index of the last capital letter in the String.

import java.util.stream.IntStream;

/**
 * Finds the index of the last uppercase letter in a String.
 */
public class FindIndexOfLastUppercaseLetter {
    public static void main(String[] args) {
        String str = "saveChangesInTheEditor";
        int lastUppercaseLetterIndex = findLastUppercaseLetter(str);
        if (lastUppercaseLetterIndex != -1) {
            System.out.println("The last uppercase letter index is " + lastUppercaseLetterIndex
                    + " which is " + str.charAt(lastUppercaseLetterIndex));
        } else {
            System.out.println("No uppercase letter was found in the String.");
        }
    }

    private static int findLastUppercaseLetter(String str) {
        int[] stringChars = str.chars().toArray();
        int stringCharsLenght = stringChars.length;
        return IntStream.range(0, stringCharsLenght)
                .map(i -> stringCharsLenght - i - 1)
                .filter(i -> Character.isUpperCase(stringChars[i]))
                .findFirst().orElse(-1);
    }
}

Sample output:

The last uppercase letter index is 16 which is E

Upvotes: 0

gnomed
gnomed

Reputation: 5565

Pattern pat = Pattern.compile("[A-Z][^A-Z]*$");
Matcher match = pat.matcher(inputString);

int lastCapitalIndex = -1;
if(match.find())
{
    lastCapitalIndex = match.start();
}

lastCapitalIndex will contain the index of the last capital letter in the inputString or -1 if no capitals exist.

EDIT NOTE: Solution formerly contained a loop, now it will work with one call to find() and no looping thanks to an improved regex. Tested new pattern as well, and it worked.

Upvotes: 6

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

You can write a method as follows:

public int lastIndexOfUCL(String str) {        
    for(int i=str.length()-1; i>=0; i--) {
        if(Character.isUpperCase(str.charAt(i))) {
            return i;
        }
    }
    return -1;
}

Upvotes: 20

efermat
efermat

Reputation: 55

You can compare each character of the string with the uppercase characters range in the ASCII table (decimal 65 ('A') to 90 ('Z')).

Upvotes: 2

Related Questions