1. Computer problem? Tech Support Guy is completely free -- paid for by advertisers and donations. Click here to join today! If you're new to Tech Support Guy, we highly recommend that you visit our Guide for New Members.

Solved: (Java) Separating Array indexes with a comma

Discussion in 'Software Development' started by Razorcane, Nov 25, 2011.

Thread Status:
Not open for further replies.
  1. Razorcane

    Razorcane Thread Starter

    Feb 19, 2009
    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.
  2. sepala


    May 20, 2010
    public class StringTest
        static String str = "This string has a comma,";
        public static void main(String[]args)
            String a = str.replaceAll("\\,(?!,*\\,)", " ");
    With this code, you will be able to replace the last comma with a space
  3. andythepandy


    Jul 2, 2006
    You could also just remove the last chatacter more simply using String.substring:

    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);
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 733,556 other people just like you!

Thread Status:
Not open for further replies.

Short URL to this thread: https://techguy.org/1028374

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice