简体   繁体   中英

Eclipse Split string in lines and remove leading and trailing spaces

I am trying to remove spaces from a string where string is divided in lines. After splitting into lines, leading and trailing spaces need to be removed. Where numbers of lines are not fixed.

What I am trying is

      String[] lines = Imgdata.split("\r\n|\r\n");

      String firstLine = lines[0].trim();
      String firstLine = lines[1].trim();

Here i am able to do for two lines. What can be done where number of lines are not fixed. It can be 4 or 5 or 6.

You should use,

 String lines[] = String.split("\\r|\\n"); 

instead. and then perform actions as you are currently doing them. :)

Use a loop, if the number of elements in the array is unknown. This will trim every string in your array. Note: the original, untrimmed strings will be lost.

String[] lines = Imgdata.split("\r\n|\r\n");

for(int i = 0; i < lines.length; i++)
    lines[i] = lines[i].trim();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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