【问题标题】:How to replace a String at a specific index in a text file in Java如何在Java中的文本文件中替换特定索引处的字符串
【发布时间】:2013-01-11 12:04:07
【问题描述】:

我的文本文件包含:

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

我想将文件中的 index{1,3} 替换为 'Sys',将 index{4,7} 替换为 'Jav' 等等。

我的想法是将整个文件作为字符串读取,然后传递索引以替换为 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);

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

【问题讨论】:

  • 这是作业吗?请适当添加标签。关于您的问题,您面临的问题是什么?
  • 我想用系统替换 index{1,3},用 Java 替换 index{4,7} 等等。如何在循环中做到这一点?
  • @sundar 自去年夏天以来,作业没有标签。
  • 你甚至没有说你想替换什么。您可以发布您想要的输出以提供帮助吗?
  • 检查已经发布的输出。 1 主要问题是第一次替换后索引被打乱了。

标签: java string file indexing


【解决方案1】:

问题解决了!代码完美运行,因为我对其进行了测试。和之前一样,没有添加任何 cmets,所以你会理解和学习。 (如果它对他人识别正确答案有用,请投票/接受答案)。

代码:

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

            }

    }
}

【讨论】:

  • 你总是有办法解决我的问题 (_)。非常感谢
  • 我也是来帮忙的。正如您从我的个人资料中看到的那样,我没有那么有经验,所以我什至在解决您的问题时学习了新东西。
  • 你能加我吗:linedsubset@live.com
【解决方案2】:

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

【讨论】:

  • 是的,replace 需要更复杂的逻辑,因为第一次替换后索引会受到干扰。
【解决方案3】:

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

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

【讨论】:

  • 仍然不正确prntscr.com/ot9fp。是否可以将整个文件作为字符串读取,然后根据给定的索引和要替换的值进行替换。
  • 您可能应该通过从每个索引中减去 1 来修复索引数组。指数从 0 开始。您的预期输出是什么?我怀疑您正在尝试与您最初的问题和代码建议的完全不同的东西。
  • 预期输出:Hello 将变为“Systemlo”等等。但正如 Marko 在第一次替换时指出的那样,索引受到了干扰。
猜你喜欢
  • 2014-06-21
  • 2021-02-14
  • 1970-01-01
  • 2011-10-20
  • 2017-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多