Visaali Sundaram Visaali Sundaram - 5 months ago 13
Java Question

How to specify the number of alphabets (and not blank spaces) to include in a substring?

I am trying to print a substring using index value. I need to exclude the blank space while counting but it should print the output along with blank space. I want to display, say, n alphabets from the main string. The blank spaces will be as they are but the number of alphabets from the lower bound to upper bound index should be n. My code is

public class Test {
public static void main(String args[])
{
String Str=new String("Welcome to the class");
System.out.println("\nReturn value is:");
System.out.println(Str.substring(2,9));
}
}


Output:
lcome t

In the above mentioned code, it counts the space between the "Welcome" and "to". i need not want to count the space between them. My expected output is lcome to

Answer

You could use simple mathematics. Just substring it, remove all whitespaces and compare the original length to the String without whitespaces. Afterwards add the difference in size to your end index for the substring.

public static void main(String args[]) {
    String Str = "Welcome to the class";
    System.out.println("\nReturn value is:");
    String sub = Str.substring(2, 9);
    String wsRemoved = sub.replaceAll(" ", "");
    String wsBegginingRemoved = sub.replaceAll("^ *", "");
    String outputSub = Str.substring(2+(sub.length()-wsBegginingRemoved.length()), 9+(sub.length()-wsRemoved.length()+(sub.length() - wsBegginingRemoved.length())));
    System.out.println(outputSub);
}

Edit: not ignoring leading whitespaces anymore

O/P

lcome to

O/P "My name is Earl"

name is E