1
public class StringDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String name = "String";
        char[] c = name.toCharArray();
        for (char ch : c) {
            System.out.print(ch);
                System.out.print(",");
        }
    }
}

This gives me output as

S,t,r,i,n,g,

I don't want that last comma, how to get output as S,t,r,i,n,g

5 Answers 5

1

You can also do it on a higher level without writing your own loop. It's not faster or anything, but the code is more clear about what it's doing: "Split my string into characters and join it back together, separated by commas!" ...

String name = "String";
String separated = String.join(",", name.split(""));
System.out.println(separated);

EDIT: String.join() is available from Java 1.8 and up.

Sign up to request clarification or add additional context in comments.

Comments

0

I would personally use a StringBuilder for this task.

What you need, is to apply some logic that can distinguish whether or not a comma is needed. You loop through the characters just like you did and you always append a comma before the next character, except on the first iteration.

Example:

public static void main(String[] args) {
    String test = "String";
    StringBuilder sb = new StringBuilder();
    for (char ch : test.toCharArray()) {
        if (sb.length() != 0) {
            sb.append(",");
        }
        sb.append(ch);
    }
    System.out.println(sb.toString());
}

Output:

S,t,r,i,n,g

Another way without StringBuilder and using just a traditional for loop, but using the same logic:

public static void main(String[] args) {
    String test = "String";
    char[] chars = test.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (i != 0) {
            System.out.print(",");
        }
        System.out.print(chars[i]);
    }
}

Output:

S,t,r,i,n,g

Comments

0

Sure, but for this you need a for loop based on the length of c, other solutions are not as straight IMHO:

String name="String";
char[] c = name.toCharArray();
for (int i = 0; i < c.length; i++){
    char ch = c[i];
    System.out.print(ch);
    if( i != c.length -1 ){
        System.out.print(",");
    }
}

Comments

0

Some additional 2 Cents:

You can stream the character int values, map them to a List<String> where each element is a single char as String and finally use String.join(..., ...) in order to get the desired result, a comma separated String of all the characters in the original String:

public static void main(String[] args) {
    // take an example String
    String name = "Stringchars";
    // make a list of characters as String of it by streaming the chars
    List<String> nameCharsAsString = name.chars()
                                        // mapping each one to a String
                                        .mapToObj(e -> String.valueOf((char) e))
                                        // and collect them in a list
                                        .collect(Collectors.toList());
    // then join the elements of that list to a comma separated String
    String nameCharsCommaSeparated = String.join(",", nameCharsAsString);
    // and print it
    System.out.println(nameCharsCommaSeparated);
}

Running this code results in the following output:

S,t,r,i,n,g,c,h,a,r,s

This is just another possibility of getting your desired result, it is not necessarily the best solution.

2 Comments

I feel like this is quite an overhead for just splitting the string. Not only that it's creating a an intermediate collection, but also the code could be much more readable by just doing name.split(""); (which returns a string array you can pass to String.join() in the same way).
Yes, you are totally right. I actually upvoted the answer that uses String.join() and name.split() because it's just simpler. I will leave this answer and comment for future readers not expecting any upvotes ;-)
0

You can use Stream to do that. Please check below,

String result = Arrays.stream(name.split("")).collect(Collectors.joining(","));

Output:

S,t,r,i,n,g

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.