如何替换Java文本文件中特定索引处的字符串



我的文本文件包含:

Hello This is a Test
Press Enter to Continue

我有一个数组:

int StartIndex [] = {1,4,8}
int EndIndex [] = {3,7,11}
String[] VALUES = new String[] {"Sys","Jav","Tes"};

我想把索引{1,3}替换为'Sys',索引{4,7}替换为' java '等等。

我的想法是将整个文件作为字符串读取,然后传递索引以替换为VALUES字符串。

我该怎么做呢?

代码:

 String[] VALUES = new String[] {"Sys"}; //Correct Solutions
 int [] StartIndex ={4};
 int [] EndIndex ={6};
 while ((line = br.readLine()) != null)   {
                  // Print the content on the console
                  System.out.println (line);
                  StringBuffer buf = new StringBuffer(line);
                  buf.replace(StartIndex[0], EndIndex[0], VALUES[0]);
                  done =buf.toString();
                  System.out.println(done);

预期输出应该是这样的:

SyslJavhTes is a Test
Press Enter to Continue

我搜索了一下,得到了这个:

String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);

如果我们将文件转换为字符串并应用此函数,这将工作吗?

问题解决!代码运行完美,因为我测试过它。像以前一样,没有添加评论,所以你会理解&学习。(如果其他人能认出正确答案,请投票/接受)

代码:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
 *
 * @author jtech
 */
public class ReplaceWithIndexes
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = null;
        boolean endMatched = false;
        int startIndex[] = {0,4,8};
        int endIndex[] = {3,7,10};
        int c = 0, c1 = 0, c2 = 0, largestVal_start = 0, largestVal_end = 0, lineCount = 0;
        String line = null, newString = "";
        String[] VALUES = new String[] {"Sys","Jav","Tes"};  
        br = new BufferedReader(new FileReader("C:\Users\jtech\Documents\NetBeansProjects\HelpOthers\src\textFiles\AnotherFile.txt"));
        for (int i = 0; i < startIndex.length; i++)
        {
            if (startIndex[i] > largestVal_start)
            {
                largestVal_start = startIndex[i];
            }
        }
        for (int i = 0; i < endIndex.length; i++)
        {
            if (endIndex[i] > largestVal_end)
            {
                largestVal_end = endIndex[i];
            }
        }       

            while ((line = br.readLine()) != null)   
            {
                StringBuilder buf = new StringBuilder(line);
                          // Print the content on the console
                System.out.println(line);
                lineCount++;
                    while (c <= largestVal_start)
                    {                       
                       while (c1 <= largestVal_end)
                       {                           
                           if (startIndex[0] == c && endIndex[0] == c1)
                           {
                             buf.replace(startIndex[0], endIndex[0], VALUES[c2]);
                             newString = buf.toString();
                             endMatched = true;
                           }
                           else if (startIndex[1] == c && endIndex[1] == c1)
                           {
                             buf.replace(startIndex[1], endIndex[1], VALUES[c2]);
                             newString = buf.toString();
                             endMatched = true;
                           }
                           else if (startIndex[2] == c && endIndex[2] == c1)
                           {
                             buf.replace(startIndex[2], endIndex[2], VALUES[c2]);
                             newString = buf.toString();
                             endMatched = true;
                           }
                         c1++;
                       }
                      for (int i = 0; i < startIndex.length; i++)
                      {
                        if (c == startIndex[i])
                        {
                            c2++;
                        }
                      }
                      if (endMatched == true || ((c1 <= largestVal_end) == false) )
                      {
                          c1 = 0;
                          endMatched = false;
                      }
                      c++;
                    }
                if (lineCount <= 1)
                {
                  System.out.println("Updated line: " + newString);
                }
            }
    }
}

在Java中,类是众所周知的锤子,每个问题都是钉子。您也需要一个数组,而不是管理三个单独的数组。

class Replacer {
  private final int start, end;
  private final String replacement;
  Replacer(int start, int end, String replacement) {
    this.start = start; this.end = end; this.replacement = replacement;
  }
  String replace(String in) {
    StringBuilder b = new StringBuilder(in);
    b.replace(start, end, replacement);
    return b.toString();
  }
}

然后创建一个替换列表:

List<Replacer> replacers = Arrays.asList(
   new Replacer(1, 3, "System"),
   new Replacer(4, 7, "Java"),
   new Replacer(8, 11, "Testing")
);

并将它们应用于每一行:

while ((line = br.readLine()) != null) {
  for (Replacer r : replacers) line = r.replace(line);
  System.out.println(line);
}

最简单的解决方案是下面的代码,但对于大文件和/或大量替换来说,它可能不够有效。

while ((line = br.readLine()) != null) {
    // Print the content on the console
    System.out.println (line);
    StringBuffer buf = new StringBuffer(line);
    for (int i = 0; i < VALUES.length; i ++) {
        buf = buf.replace(StartIndex[i], EndIndex[i], VALUES[i]);
    }
    done = buf.toString();
    System.out.println(done);
}

相关内容

  • 没有找到相关文章

最新更新