Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid printing the last comma

Tags:

java

I'm trying to print this loop without the last comma. I've been Googling about this and from what i've seen everything seems overcomplex for such a small problem. Surely there is an easy solution to avoid printing the last comma. Much appreciated if somebody could help me out, this is driving me insane!!!

For example it loops from 1-10 // 1,2,3,4,5,6,7,8,9,10, < do not want this last comma

public static void atob(int a,int b)
{
    for(int i = a; i <= + b; i++) 
    {
        System.out.print(i + ",");
    }
}
like image 417
OMGjava Avatar asked Apr 03 '12 10:04

OMGjava


People also ask

How do you remove the last comma from a comma separated string?

Using the substring() method We remove the last comma of a string by using the built-in substring() method with first argument 0 and second argument string. length()-1 in Java. Slicing starts from index 0 and ends before last index that is string.

How to remove the last comma in Python?

rstrip() method to remove the last comma from a string, e.g. new_str = my_str. rstrip(',') . The str. rstrip() method will return a copy of the string with the trailing comma removed.


2 Answers

I might get stoned to death for this answer

public static void atob(int a,int b) {
  if(a<=b) {
    System.out.println(a);
      for(int i = a+1;i<=b;i++) {
        System.out.println(","+i);
      }
    }
  }
}  
like image 65
Aadi Droid Avatar answered Oct 19 '22 23:10

Aadi Droid


Yet another way to do this.

String sep = "";
for(int i = a; i <= b; i++) {
    System.out.print(sep + i);
    sep = ",";
}

if you are using a StringBuilder

StringBuilder sb = new StringBuilder();
for(int i = a; i <= b; i++)
    sb.append(i).append(',');
System.out.println(sb.subString(0, sb.length()-1));
like image 45
Peter Lawrey Avatar answered Oct 19 '22 21:10

Peter Lawrey