Visaali Sundaram Visaali Sundaram - 3 months ago 5
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:");

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


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())));

Edit: not ignoring leading whitespaces anymore


lcome to

O/P "My name is Earl"

name is E