Untitled
unknown
plain_text
a month ago
11 kB
3
Indexable
public class UserString { private String str; public UserString(String str) { this.str = str; } // a) Count all the characters public int countCharacters() { return str.length(); } // b) Count no of words public int countWords() { if (str == null || str.isEmpty()) { return 0; } String[] words = str.split("\\s+"); // Split by one or more spaces return words.length; } // c) Compare two strings public boolean compareStrings(UserString other) { return str.equals(other.str); } // d) Convert to uppercase public String toUppercase() { return str.toUpperCase(); } // e) Convert to lowercase public String toLowercase() { return str.toLowerCase(); } // f) Concatenate two strings public String concatenate(UserString other) { return str.concat(other.str); } // g) Check a string is palindrome or not public boolean isPalindrome() { String reversed = new StringBuilder(str).reverse().toString(); return str.equals(reversed); } // h) Find the position of a given character public int findPosition(char ch) { return str.indexOf(ch); } // i) Make a substring from a desired start and end position. public String makeSubstring(int start, int end) { return str.substring(start, end); } // j) Search the presence of a substring. public boolean searchSubstring(String sub) { return str.contains(sub); } // k) Replace a substring with a new string. public String replaceSubstring(String oldSub, String newSub) { return str.replace(oldSub, newSub); } // l) Swap two substrings between two strings. public static String swapSubstrings(String str1, String sub1, String str2, String sub2) { String temp = str1.replace(sub1, sub2); return str2.replace(sub2, sub1); } public static void main(String[] args) { UserString str1 = new UserString("Hello World"); UserString str2 = new UserString("hello world"); System.out.println("String 1: " + str1.str); System.out.println("String 2: " + str2.str); System.out.println("Character count: " + str1.countCharacters()); System.out.println("Word count: " + str1.countWords()); System.out.println("Compare strings: " + str1.compareStrings(str2)); System.out.println("Uppercase: " + str1.toUppercase()); System.out.println("Lowercase: " + str1.toLowercase()); System.out.println("Concatenated: " + str1.concatenate(str2)); System.out.println("Is palindrome: " + str1.isPalindrome()); System.out.println("Position of 'o': " + str1.findPosition('o')); System.out.println("Substring (0, 5): " + str1.makeSubstring(0, 5)); System.out.println("Contains 'World': " + str1.searchSubstring("World")); System.out.println("Replace 'World' with 'Java': " + str1.replaceSubstring("World", "Java")); String string1 = "This is string one"; String string2 = "This is string two"; String swapped = swapSubstrings(string1, "one", string2, "two"); System.out.println("Swapped strings: " + swapped); } } } } } } } } } } } } } } } } } }
Editor is loading...
Leave a Comment