我正在尝试使用索引值打印子字符串。我需要在计数时排除空格,但它应该连同空格一起打印输出。我想显示主字符串中的 n 个字母。空格将保持原样,但从下限到上限索引的字母数应为 n。我的代码是
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));
}
}
输出: 我来了
在上面提到的代码中,它计算了“Welcome”和“to”之间的空格。我不需要计算它们之间的空间。我的预期输出是lcome to
最佳答案
您可以使用简单的数学。只需对其进行子字符串化,删除所有空格并将原始长度与没有空格的 String
进行比较。然后将大小差异添加到子字符串的结束索引中。
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);
}
编辑:不再忽略前导空格
O/P
lcome to
O/P “我叫厄尔”
name is E
关于java - 如何指定要包含在子字符串中的字母数(而不是空格)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38217706/