如何删除从excel导入的字符串中的空白

ajsxfq5m  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(304)

我需要删除所有白色字符从字符串,我不能这样做。有人知道怎么做吗?
以下是通过jxl api从excel文件检索到的字符串:

"Destination à gauche"

下面是它的字节:

6810111511610511097116105111110-96-32321039711799104101

下面是我用来删除空白的代码:

public static void checkEntetes(Workbook book) {
        String sheetName = "mysheet";
        System.out.print(sheetName + " : ");
        for(int i = 0; i < getColumnMax(book.getSheet(sheetName)); i++) {
            String elementTrouve = book.getSheet(sheetName).getCell(i, 0).getContents();
            String fileEntete = new String(elementTrouve.getBytes()).replaceAll("\\s+","");
            System.out.println("\t" + elementTrouve + ", " + bytesArrayToString(elementTrouve.getBytes()));
            System.out.println("\t" + fileEntete + ", " + bytesArrayToString(fileEntete.getBytes()));
        }
        System.out.println();
}

这个输出:

"Destination à gauche", 6810111511610511097116105111110-96-32321039711799104101
"Destination àgauche", 6810111511610511097116105111110-96-321039711799104101

我甚至试着自己做,但它仍然留有一个空间前的'à' 烧焦。

public static String removeWhiteChars(String s) {
    String retour = "";
    for(int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if(c != (char) ' ') {
            retour += c;
        }
    }
    return retour;
}
qgelzfjb

qgelzfjb1#

解救正则表达式:

str = str.replaceAll("\\s+", "")

将删除任何空格字符序列。例如:

String input = "Destination à gauche";
String output = input.replaceAll("\\s+","");
System.out.println("output is \""+output+"\"");

输出 Destinationàgauche 如果你的起点确实是原始字节( byte[] )您首先需要将它们做成一个字符串:

byte[] inputData = //get from somewhere
String stringBefore = new String(inputData, Charset.forName("UTF-8")); //you need to know the encoding
String withoutSpaces = stringBefore.replaceAll("\\s+","");
byte[] outputData = withoutSpaces.getBytes(Charset.forName("UTF-8"));
0ve6wy6x

0ve6wy6x2#

如果您想使用公式,trim函数将完全满足您的要求:

+----+------------+---------------------+
|    |     A      |           B         |
+----+------------+---------------------+
| 1  | =TRIM(B1)  |  value to trim here |
+----+------------+---------------------+

整个专栏也是如此。1) 插入一列2)插入修剪函数指向您要更正的单元格。3) 将公式复制到下一页4)复制插入的列5)粘贴为“值”
参考:stackoverflow.com上的问题编号9578397

相关问题