简体   繁体   English

分割字符串并删除Java中的第二个空格

[英]Split string and delete every second space in java

I have log data in a raw file. 我在原始文件中有日志数据。 It looks like this: 看起来像这样:

"2 A U W 2 0 1 1 1 1 1 6 0 0 1 0 0 0        U S E R N 1      F T Y 0 0 0 0 0 0 D 9         2 A I L 2 0 1 1 1 1 1 6" 

and so on. 等等。

I need to substring this string on messages of equal length (From "2 AUW" to "4 AIL" 400 bytes). 我需要在相等长度的消息上对这个字符串进行子字符串化(从“ 2 AUW”到“ 4 AIL” 400字节)。 This is made by String as = s.substring(0,400).toLowerCase() . 这是通过String as = s.substring(0,400).toLowerCase() But this is not enough for me. 但这对我来说还不够。 I want to make a message like this: 我想发出这样的消息:

2auw 
20011111600100 
usern1 
fty000000d9

Can anyone help with it? 有人可以帮忙吗?

This will get your work done. 这样就可以完成您的工作。 If you are having a lot of data like the above line, we will have to figure some other logic. 如果您有大量数据(如上一行),我们将不得不考虑其他逻辑。 I don't think it will be apt for millions of records. 我认为它不适合数百万条记录。

String asd = "2 A U W 2 0 1 1 1 1 1 6 0 0 1 0 0 0        U S E R N 1      F T Y 0 0 0 0 0 0 D 9         2 A I L 2 0 1 1 1 1 1 6";
asd = asd.replaceAll("      ", "\n");
asd= asd.replaceAll(" ", "");
System.out.println(asd);

Please note the space between "USERN 1" and "FTY 0 0 0 0 0 0 D 9" is having minumum number of simultaneous spaces. 请注意, "USERN 1""FTY 0 0 0 0 0 0 D 9"的空格具有最少的同时空格数。 So, I have used that number of spaces to insert new line character. 因此,我已使用该数量的空格来插入换行符。
The logic will result in wrong output if space between characters is greater than two times this <6 space> string. 如果字符之间的间距大于此<6 space>字符串的两倍,则逻辑将导致错误的输出。 ie: there will be <12 spaces> continuously. 即:将连续存在<12 spaces>
To solve that you can insert this code just before printing. 为了解决这个问题,您可以在打印之前插入此代码。 But use it only if such data happens. 但是仅在发生此类数据时才使用它。

asd= asd.replaceAll("\n\n", "\n");

You can add a back slash n "\\n" to add line breaks to your string. 您可以添加反斜杠n“ \\ n”以在字符串中添加换行符。

I'm not sure if this is the best way, but it is one way to do it: If you know where you need the line breaks you can substring and add the back slash n. 我不确定这是否是最好的方法,但它是实现此目的的一种方法:如果您知道在何处需要换行符,则可以将其子串并添加反斜杠n。 Something like this: 像这样:

String s = as.substring(0,4) + "\n" + as.substring(4,18) + "\n" + //....and so on

Hope it helps 希望能帮助到你

Have you tried: 你有没有尝试过:

String[] split = s.split("\\s+");

You may need to tweak the reg-exp. 您可能需要调整reg-exp。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM