FileStringSearch - 用空格字符替换换行符

时间:2018-02-11 00:03:49

标签: java string search

我试图弄清楚这段代码有什么问题:

我正在调用getCol(file,keyword,1,1)并且函数是(getCol实际上返回一个带有line和col的数组,抱歉表示符号):

public static int[] getCol(String file, String keyword, int startLine, int startCol) {
 int[] res = findCol(file, keyword, startLine, startCol);
 if(res[0]>0) return res;
 else if (res[0]<0) { // if wrong word
   while(res[0]<0) { // search again starting at resCol+1
     res = findCol(file,keyword,startLine,-res[0]+1);
   }
  return res;
 } else return emptyArr;
}


public static int[] findCol(String file, String keyword, int startLine, int startCol) {
StringBuilder match = new StringBuilder("");
int curCol = 0;
int curLine = 1;
int r = 0;
BufferedReader in = null;

try {
in = new BufferedReader(new FileReader(file));
for(int i=1; i<startLine; i++) { in.readLine(); } // skip lines until startLine
while ((r=in.read())!=-1) {
  char c = (char) r;
  curCol += 1;
  if(startCol>1 && curCol<startCol) {
    for(int k=1; k<startCol; k++) {
      curCol += 1;
      c = (char) in.read(); // skip chars until startcol
    } // for (skip cols) end
  }
  if(c == keyword.charAt(0)) {
    match.append(c);
    System.out.println("match: "+match);
    for(int i=1; i<=keyword.length()-1; i++) { 
      int m = in.read();
      c = (char) m; //System.out.println("c: "+c);
      if(c == '\n') {
        match.append(" ");
      } else match.append(c);
      System.out.println("match: "+match);
    } // for end
    int[] retSuccess = {curCol, curLine};
    int[] retFailure = {-curCol, curLine};
    if(match.equals(keyword)) {
     return retSuccess;} // Coloumn found
    else {
    return retFailure; } // if first character is the same but word is different return -curCol and run findCol() again but starting at curCol+1
  }
} // while end

in.close();
} catch(IOException ioe) {
    System.out.println(ioe);
} //try-catch end
return emptyArr;
} // findCol() end

我实际上只想检查某个字符串(关键字)是否出现在包含多个句子的文件中。这个关键字可以写成几行。例如。我试图找到密钥&#34; mini Text&#34;在原文&#34; mini \ nText&#34; (&#34;微型[换行符]文本&#34)。我试图替换任何&#39; \ n&#39;带有空格字符的字符(&#39;&#39;)但它的反应非常奇怪:

我期待着这个:

match: m
match: mi
match: min
match: mini
match: mini  (actually mini+" ")
match: mini T
match: mini Te
match: mini Tex
match: mini Text

我正面对这个:

match: m
match: mi
match: min
match: mini
match: mini
 atch: mini
 Ttch: mini
 Tech: mini
 Texh: mini
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at StringSearchAbsNew.getCol(StringSearchAbsNew.java:58)
    at StringSearchAbsNew.main(StringSearchAbsNew.java:45)

如果有人可以帮助我,我将非常感激..我不再有任何指甲了,而且我不会进一步了解..

提前致谢,祝你有个美好的一天!

0 个答案:

没有答案