所以这就是问题所在。将文本文件转换为正确的格式。
问题的关键在于我必须读取一个文件,一个文本文件,其中包含该文本文件中的代码。其中的代码格式很糟糕。格式问题是当有一个像{
这样的大括号时,下一行不是右边的4个空格,它只是在最左边。像这样:
while (blah blah blah) {
sysout(blahblahblah);
应该如此:
while (blah blah blah) {
sysout(blahblahblah);
并且2之间没有其他区别。唯一的规则就是每次有像这样的大括号时都这样做,以确保下一行是右边的4个空格。反之亦然。因此,每次有像这样的大括号时,下一行应该是左边的4个空格。我希望你们明白这一点。
这是我的问题。我学会了如何创建一个程序,其中一个带有多个空格和行的文本被转换为一行,每次都有一个空格。太难了。
但是,为此,我必须将所有内容保持在同一条线上。因此,如果有30行,我制作的新节目也是30行。我需要保持非常相似的间距,但简单的区别是整个支撑物。所以基本上,我只需要在一个括号后面的行向右移动4个空格,然后做同样的操作,这样如果它是一个}
花括号,它就是左边4个空格。
那么我该怎么做呢?我不知道如何在不搞乱其他事情的情况下解决这个问题。这是我必须要做的一件简单的事情;只是使大括号4后面的行向右或向左,但我只是不知道用什么语法来实现这一点。谢谢!
编辑:这可能会让它变得更容易。因此,基本上,所有线条都以右大括号,左大括号或分号结束。无论。因此,每当其中一个弹出时,它就是一条线的终点。所以,如果你知道如何让它变得更容易,那么我只是让你知道。
答案 0 :(得分:0)
有些程序会自动为您执行此操作,因此您无需重新发明轮子。例如,在Eclipse中,键入:ctrl-a
(全选)ctrl-i
(自动缩进)。
答案 1 :(得分:0)
这是一个你可以开始的伪代码:
int indentLevel = 0;
while(currentchar = nextchar != null){
printCurrentChar
if(currentchar is '{'){
indentLevel++;
}else if(currentchar is '}'){
indentLevel--;
}else if(currentchar is '\n'){
print indentLevel * 4 spaces
}
}
你可能需要处理逃脱的牙箍和其他并发症
答案 2 :(得分:0)
您可以使用正则表达式轻松完成此操作。如果您不了解并计划成为程序员,那么一定要学习它。这将为您节省大量时间。
public class TextIndentator
{
public static void main(String[] args) throws IOException
{
File uglyText = new File("ugly.txt");
System.out.println((uglyText.exists() && !uglyText.isDirectory()) ? getNiceText(uglyText) : "FILE \"ugly.txt\" at " + System.getProperty("user.dir") + " do not exists");
}
static String getNiceText(File uglyText) throws IOException
{
// Opening file
FileInputStream inputStream = new FileInputStream(uglyText);
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(isr);
StringBuilder builder = new StringBuilder();
StringBuffer buffer = new StringBuffer();
// Algorithm starts here
String line;
boolean checkNext = false;
while ((line = reader.readLine()) != null)
{
if(checkNext)
{
// If previous line finished with '{' (And optionally with some whitespaces after it) then, replace any amount (including zero) of whitespaces with 4 witespaces
builder.append(line.replaceFirst("\\s*", " "));
}
else
{
builder.append(line);
}
// Check if line line finishes with { (And optionally with some whitespaces after it)
if(line.matches(".*\\{\\s*")) checkNext = true;
else checkNext = false;
//Append line separator at the end of line
builder.append(System.getProperty("line.separator"));
}
return builder.toString();
}
}