Untitled

 avatar
unknown
plain_text
a year ago
1.3 kB
3
Indexable
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.");
        }
    }
}
Editor is loading...
Leave a Comment