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 + ",");
}
}
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.
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.
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);
}
}
}
}
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With