Java string.split () function separator carriage return considerations

Source: Internet
Author: User

In Java, if we use the processing to separate strings, we will inevitably use the string's split (string regex) function, which we should pay attention to.

Many students do this if they want to separate the strings with a carriage return. Here is an example:

string[] res = str.split ("\ n");

However, there may be a potential problem, if our str string is obtained from a text file, then there is a hidden danger.

If our file is Test.txt, the contents are:

This (enter)

is testing (no carriage return)

That's the problem.

1, if the file is written under Linux or Mac, then use Str.split ("\ n") will appear the correct results, such as:


2, if the file is written under window, then it should be noted that if you still use Str.split ("\ n") will be the wrong result, such as:

Some people may say that there is no difference ah, carefully watch, the result of the 2nd, this and is testing in the middle of a blank line, and the first one does not. Why this result is present.

This also from the carriage return, in short, the window next car is composed of \ r \ n (ie, 0x0d and 0x0a), note is not \n\r, and Linux next car is \ n (that is, 0x0a) small partners do not make a mistake, this I have confirmed,

This window under the editing file, I use 16 binary open, you see the 3rd, 4 column is 0D, 0A, that is, enter.

And that's what it looks like under Linux:



This is the Linux file with 16 binary open case, the red circle only a 0 A, that is, enter.

Here we understand that, just under window with the split ("\ n") results appear, is this\r and is testing two parts.

The result of using split ("\ n") in Linux is that this and is testing two parts, and this does not have a \ r behind it.

The details of this hidden danger, but also pay more attention.

Finish....

Java string.split () function separator carriage return considerations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.