簡體   English   中英

如何在Java中的文本文件中的特定索引處替換字符串

[英]How to replace a String at a specific index in a text file in 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"};

我想在文件中用“ Sys”替換索引{1,3},用“ Jav”替換索引{4,7},依此類推。

我的想法是將整個文件讀取為字符串,然后傳遞索引以替換為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);

預期的Ouput應該是這樣的:

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);
                }

            }

    }
}

最簡單的解決方案是以下代碼,但對於大型文件和/或大量替換操作,效率可能不夠。

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);
}

在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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM