given string is '_home sweet home__' if user enter the mode as 0 then o/p should be 'home sweet home__' if user enter the mode as 1 then o/p should be '_home sweet home' if user enter the mode as 2 then o/p should be 'home sweet home'.
Code
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
String str=sc.nextLine();
System.out.println("Enter the StringMode");
String strMode= sc.nextLine();
switch()
{
}
i want to find total number of white spaces in the given string.
You could try something like this:
It makes use a of the method Character#isWhitespace to check whether a character is white space or not and a StringBuilder to build the result. The return value is the number of white paces removed.
If you want to have a method to just count the white spaces in a string you can loop over the entire string, check each character using Character#isWhitespace and increment a variable if it return true.
Finally here is some testing:
Try this
A simple way :
Do this to remove all the whitespaces. Then, subtract the length of the second string from the length of the first to determine the total number of whitespaces removed.
If you want to remove only the preceding whitespace, use "^\\s+". To remove trailing, use "\\s+$".
A regex-based solution to capture your whitespaces and then rebuild the string according to the mode you need. No loops but requires some knowledge.
It uses named capturing groups to extract your whitespace and reluctant quantifier to get all the text before trailing whitespace characters. See Pattern documentation for capturing groups and this tutorial to get how quantifiers work.