在Java中展开选项卡

时间:2012-07-30 13:45:49

标签: java string whitespace

您是否知道将文本的字符扩展为空格的java方法?

我的文字:

1. <tab>  firstpoint  <tab> page  1
10. <tab> secondpoint <tab> page 10

如果我直接替换标签,比方说4个空格,我会有

1.    firstpoint    page1
10.    secondpoint    page2

而不是它,我需要一个方法来替换每个选项卡的实际对应的空格数(作为命令:vim的retab)。任何解决方案?

5 个答案:

答案 0 :(得分:4)

虽然可能有一个库可以做到这一点,但手动解决方案非常简单:

  1. 创建输出缓冲区(StringBuilder)。
  2. 遍历字符串的字符
  3. 对于每个字符,检查它是否为标签 一个。如果它不是选项卡,请将其添加到输出缓冲区 湾如果它是一个制表符,则首先添加一个空格,然后输出缓冲区长度所需的空格数为4.(您的制表符长度。)
  4. 返回输出缓冲区。

答案 1 :(得分:4)

我认为上面的retab()函数可能存在问题,而忽略了初始标签。我做了自己的;特此置身于公共领域。

public static String expandTabs(String s, int tabSize) {
    if (s == null) return null;
    StringBuilder buf = new StringBuilder();
    int col = 0;
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        switch (c) {
            case '\n' :
                col = 0;
                buf.append(c);
                break;
            case '\t' :
                buf.append(spaces(tabSize - col % tabSize));
                col += tabSize - col % tabSize;
                break;
            default :
                col++;
                buf.append(c);
                break;
        }
    }
    return buf.toString();
}

public static String spaces(int n) {
    StringBuilder buf = new StringBuilder();
    for (int sp = 0; sp < n; sp++) buf.append(" ");
    return buf.toString();
}

答案 2 :(得分:1)

我没有在网上找到任何实现,所以我自己写了关于biziclop的想法:

/**
 * Replace the tabulator characters of a String by the corresponding number of spaces.
 * Example:<pre>
 *   1.&lt;tab&gt;firstpoint&lt;tab&gt;page  1
 *   10.&lt;tab&gt;secondpoint&lt;tab&gt;page 10 </pre>
 * will become<pre>
 *   1.      firstpoint      page  1
 *   10.     secondpoint     page 10</pre>
 *
 * @param text     the text
 * @param tabstop  the espacement between the tab stops, typically 4 or 8
 * @return The text, with no &lt;tab&gt; character anymore
 */
public static String retab(final String text, final int tabstop)
{
    final char[] input = text.toCharArray();
    final StringBuilder sb = new StringBuilder();

    int linepos = 0;
    for (int i = 0; i<input.length; i++)
    {
        // treat the character
        final char ch = input[i];
        if (ch == '\t')
        {
            // expand the tab
            do
            {
                sb.append(' ');
                linepos++;
            } while (linepos % tabstop != 0);
        }
        else
        {
            sb.append(ch);
            linepos++;
        }

        // end of line. Reset the lineposition to zero.
        if (ch == '\n' || ch == '\r' || (ch|1) == '\u2029' || ch == '\u0085')
            linepos = 0;

    }

    return sb.toString();
}

答案 3 :(得分:0)

我使用Java 8 Streams重写The ANTLR Guy's answer,同时使用Alexis C.'s Streams-based code to repeat a string

static String repeatString(String s, int count) {
   return Stream.generate(() -> s).limit(count).collect(Collectors.joining());
}

static String expandTabs(String s, int tabSize) {
   int[] col = new int[1];
   return s.chars().mapToObj(c -> {
      switch (c) {
         case '\t':
            int expandBy = tabSize - col[0] % tabSize;
            col[0] += expandBy;
            return repeatString(" ", expandBy);
         case '\n':
            col[0] = 0;
            break;
         default:
            col[0]++;
      }
      return String.valueOf((char) c);
   }).collect(Collectors.joining());
}

答案 4 :(得分:0)

Eldar(Abusalimov,Terence Parr)的帖子上的变化。

更改:
1。将if语句分为两行,以便可以在正文上设置断点
2。使用StringBuffer的容量构造函数帮助它预分配存储空间。

public static String expandTabs(String str, int tabSize) {
    if (str == null)
        return null;
    StringBuilder buf = new StringBuilder(str.length()+tabSize);
    int col = 0;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        switch (c) {
            case '\n' :
                col = 0;
                buf.append(c);
                break;
            case '\t' :
                buf.append(spaces(tabSize - col % tabSize));
                col += tabSize - col % tabSize;
                break;
            default :
                col++;
                buf.append(c);
                break;
        }
    }
    return buf.toString();
}

public static StringBuilder spaces(int n) {
    StringBuilder buf = new StringBuilder(n);
    for (int sp = 0; sp < n; sp++)
        buf.append(" ");
    return buf;
}