Split and Replace methods in java

2019-08-01 13:18发布

I have data in MySQl database i want to retrieve it by splitting spaces and replace it with comma, and each 6 points i want to make it new line,but without comma

458.41016 425.70843 427.74316 392.55343 403.93516 370.91243 
399.48516 366.83843 398.54916 368.02743 397.41516 372.27043 
394.75116 382.25643 392.96616 392.69543 391.09516 402.03043 
390.35916 405.62343 389.79116 406.92443 392.62616 409.52743 
406.00316 421.83343 442.19716 458.07143 444.89016 482.76843 
431.76716 528.31343 393.39116 574.56743 350.22516 594.56743 
316.63916 610.12643 278.88716 614.34043 242.18316 610.35243 
232.12112 609.27843 228.38012 619.29143 238.47016 621.92243 
274.01216 631.28543 320.32416 637.73643 356.57416 628.91043 
420.03416 613.46343 456.48216 533.71643 457.61616 470.82943

i've tried this, How can i get it in proper way?

int sum=0;
String values = null;
    while (rs.next()) {

      values = rs.getString(1);
      String[] valueTokens = values.split("\\s");
      for(int i=0;i<valueTokens.length;i++){
      System.out.print(valueTokens[i]);
      System.out.print(",");

      if( i % 6 == 0 ) {
         System.out.println();
         sum += i; }
    }
}

标签: java string
3条回答
爷、活的狠高调
2楼-- · 2019-08-01 13:26

uses comma replace space

line.replaceAll(" ", ",");
查看更多
祖国的老花朵
3楼-- · 2019-08-01 13:46

You should print comma when i % 6 != 0, otherwise you should print a new line.

if (i % 6 != 0) {
    System.out.print(",");
} else if (i > 0 && i % 6 == 0) {
    System.out.println();
    sum += i;
}
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-08-01 13:47

If I understand your question more clearly,

each 6 points i want to make it new line,but without comma

You need to print only 6 numbers in a line and after 6th number a new line is needed,

String values = null;
int NoOfValuesPrinted = 0;
while (rs.next()) 
{
    values = rs.getString(1);
    String[] valueTokens = values.split("\\s");
    for(int i=0;i<valueTokens.length;i++)
    {
        System.out.print(valueTokens[i]);
        NoOfValuesPrinted++;
        if(NoOfValuesPrinted % 6 == 0)
        {
            System.out.println();
            NoOfValuesPrinted = 0;
        }
        else
            System.out.print(",");
    }
}
查看更多
登录 后发表回答