Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.3 kB
1
Indexable
Never
public class StringOperations {
    public static void main(String[] args) {
        // Create and initialize a string
        String str = "Hello, abc! This is a sample string with abc substring.";

        // a) Length of the string
        int length = str.length();
        System.out.println("Length of the string: " + length);

        // b) Number of 'a's in the string
        int numOfAs = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == 'a' || str.charAt(i) == 'A') {
                numOfAs++;
            }
        }
        System.out.println("Number of 'a's in the string: " + numOfAs);

        // c) Convert all lowercase to uppercase and vice versa
        String uppercaseStr = str.toUpperCase();
        String lowercaseStr = str.toLowerCase();
        System.out.println("Uppercase string: " + uppercaseStr);
        System.out.println("Lowercase string: " + lowercaseStr);

        // d) Find if the substring pattern "abc" is present and display the first position of occurrence
        int index = str.indexOf("abc");
        if (index != -1) {
            System.out.println("Substring 'abc' found at position: " + index);
        } else {
            System.out.println("Substring 'abc' not found.");
        }
    }
}
Leave a Comment