在java中打印带有空格的字符串

时间:2014-12-16 18:05:04

标签: java

我有一个txt文件。有像

这样的行
       if(true) return true;

我需要从前面的

空格中获取子字符串
"         if(true) "

和另一个子字符串

" retrun true;  "

我正在使用scanner类读取此行并分配给字符串。从该字符串我将其转换为toCharArray。我尝试过使用toCharArray [],但空格被忽略了。如何使用toCharArray

从前面的空格中获取子字符串

请任何人帮我解决这个问题

提前致谢。

2 个答案:

答案 0 :(得分:0)

您可以使用StringReader:

String str = "Some String";
int numberOfChars = str.length();
StringReader sr = new StringReader(str);
char[] chars = new char[numberOfChars];
int i = 0, read = 0;

try {
    while ((read = sr.read()) != -1) {
        chars[i] = (char)read;
        i++;
    }
} catch (IOException e) {
    // handle the exception
}

这将读取所有字符,而不会跳过任何字符。

编辑: 既然我明白你要做什么,我建议你为你的指示定义一个语法。通过这种方式,您应该能够识别这两个单独的陈述或说明。我建议你使用编译器构建工具,例如ANTLR

答案 1 :(得分:0)

我通过使用正则表达式找到了一个解决方案。答案如下

public class Test{
  public static void main(String[] args){
     String str = "     TestProgram";
     Pattern pattern = Pattern.compile("\\s*[a-zA-Z0-9]+$");
     Matcher matcher = pattern.matcher(str);
     while(matcher.find()){
         System.out.println(0,matcher.end());
     }
   }
} 

由于