Solved: (Java) Separating Array indexes with a comma

Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

Razorcane

Thread Starter
Joined
Feb 19, 2009
Messages
128
I have an String[] array that holds information gathered from a text file. Each index is a different line. I need to output all of the indexes on the string, separated by a comma. The general idea is this:

data1, data2, data3

All values in the array should be separated via a comma, except for the last value. I already tried a for loop, and using a string with the += operator, but that applies a comma to the last value as well. Any help would be appreciated.
 
Joined
May 20, 2010
Messages
4,040
Code:
public class StringTest
{
    static String str = "This string has a comma,";
    
    public static void main(String[]args)
    {
        String a = str.replaceAll("\\,(?!,*\\,)", " ");
        System.out.println(a);
    }
    
  
}
With this code, you will be able to replace the last comma with a space
 
Joined
Jul 2, 2006
Messages
379
You could also just remove the last chatacter more simply using String.substring:

Code:
String sa[] = {"hi", "there", "how", "are", "you", "today"};
String s = new String();
//your loop to join values together with commas
for(int i = 0; i < sa.length; i++)
	s += sa[i] + ",";
//s now is "hi,there,how,are,you,today,"

//remove last character
s = s.substring(0, s.length() - 1);

System.out.println(s);
 
Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 807,865 other people just like you!

Latest posts

Members online

Top