Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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

like image 340
Visaali Sundaram Avatar asked Dec 19 '22 15:12

Visaali Sundaram


2 Answers

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    
like image 149
SomeJavaGuy Avatar answered Dec 21 '22 04:12

SomeJavaGuy


One way would be to extract it to using a regex ^.{2}([^ ] *){7}.

Another option is to use a simple for loop to traverse the string and calculate the end point to use for substring.

int non_whitespace = 0; int i;
for(i = 2; non_whitespace < 7; ++non_whitespace, ++i) { 
    while (str.charAt(i) == ' ') ++i;
}
return str.substring(2, i);

It is up to you which method do you consider more readable, and assess which one leads to better performance if speed is a concern.

like image 22
majk Avatar answered Dec 21 '22 05:12

majk