简体   繁体   中英

Split string array using comma delimeter in java

I have a string array --> string[] arr={"CSE01A","ECE02B","MECH03C"};

Now I have to print course= CSE01, ECE02,MECH03 and grade= 'A','B','C'

I tried to use split() using the comma delimiter but that is not working for an array of strings..

Please let me know how to do this.

That's because there's no comma delimiter in what you're trying to split.

You need to loop through the array elements and grab the last character of each string.

for (String s : arr) {
    int l = s.length();
    String course = s.substring(0, l-1);
    String grade = s.substring(l-1);
}

For completeness:

List<String> courses = new ArrayList<String>();
List<String> grades = new ArrayList<String>();
for (String s : arr) {
    int l = s.length();
    courses.add(s.substring(0, l-1));
    grades.add(s.substring(l-1));
}
System.out.println(StringUtils.join(courses, ", "));
System.out.println(StringUtils.join(grades, ", "));

Java's split() takes a String and splits it into an array, eg ("abc,def,ghi").split(",") gives you a String[] with "abc", "def", "ghi". You need to take each String in your array and split the last letter (the grade) off. If you just want to print it out:

for(String s : arr) {
    String course = s.substring(0,s.length()-1);
    String grade = s.substring(s.length()-1);

    System.out.println("Course: "+course+" Grade: "+grade);
}

You don't need to split, you must combine the array elements to an string.

    String[] arr={"CSE01A","ECE02B","MECH03C"};

    StringBuilder coursesBuilder = new StringBuilder();
    StringBuilder gradeBuilder = new StringBuilder();
    String[] arr = new String[0];
    for (int i = 0; i < arr.length; i++) {

        String course = arr[i].substring(0, arr.length - 1);
        String grade = arr[i].substring(arr.length - 1);
        coursesBuilder.append(course);
        gradeBuilder.append("'" + grade + "'");

        boolean hasNext = (i + 1) < arr.length;
        if (hasNext) {
            coursesBuilder.append(", ");
            gradeBuilder.append(", ");
        }
    }

    String courses = coursesBuilder.toString();
    String grades = gradeBuilder.toString();

split() is Sting's method that accepts string and creates array. If you want to use it you should say str.split("\\\\s*,\\\\s*") - this is safe for spaces.

But you already have array, so you just want to print it. You can use Arrays.toString(arr) .

the array is already split, it is not a string. In order to print you would loop through the elements:

for ( String courseAndGrade : arr ) {
    // split the course and grade:

    System.out.println( ... );
}

Your course list isn't a string that contains commas so you can't simply "split" them. You can iterate over an array with code that looks like this:

for(int i=0; i < arr.length; i++){
    String packedString = arr[i];
}

on each iteration of the loop, the variable packedString will contain your course number and grade (ie CSE01A on the first iteration of the array). So you just need to apply an method to unpack the data. If a grade is always just a single character, you can use substring to parse out the last character and everything before it, but if you have multi-character grades (A-, for instance) you'll need to do something a little more complex.

I hesitate to expand further as this sounds like homework.

The problem is, you don't have a delimiter for each course, the course and the grade are together in the same String.

Since you know that the grade is at the end, you could do something simple like this:

String[] arr = {"CSE01A","ECE02B","MECH03C"};
String[] courses = new String[arr.length];
char[] grades = new char[arr.length];

for (int i = 0; i < arr.length; i++) {
    courses[i] = arr[i].substring(0, arr[i].length() - 1);
    grades[i] = arr[i].charAt(arr[i].length()-1);           
}

At the end, you'll have a String[] with the courses and a char[] with their respective grades.

This will iterate through your array and output your courses and grades:

StringBuilder courses = new StringBuilder();
StringBuilder grades = new StringBuilder();
String delimiter = "";

for (String s : arr) {
    courses.append(delimiter).append(s.subSequence(0, s.length() - 1));
    grades.append(delimiter).append("'").append(s.substring(s.length() - 1)).append("'");
    delimiter = ",";
}


System.out.println("Courses: " + courses.toString()); // prints CSE01,ECE02,MECH03
System.out.println("Grades: " + grades.toString()); // prints 'A','B','C'

You could use Guava to help simplify the effort to handle the string transformations and to stitch the results together:

package testCode;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

public class TestMain {

    static Joiner joinWithComma = Joiner.on(", ").skipNulls();

    private static String getCourses(Iterable<String> fromArray) {
        return joinWithComma.join(Iterables.transform(fromArray,
                new Function<String, String>() {
                    @Override
                    public String apply(String arg0) {
                        return arg0.substring(0, arg0.length() - 1);
                    }
                }));
    }

    private static String getGrades(Iterable<String> fromArray) {
        return joinWithComma.join(Iterables.transform(fromArray,
                new Function<String, String>() {
                    @Override
                    public String apply(String arg0) {
                        return arg0.substring(arg0.length() - 1, arg0.length());
                    }
                }));
    }

    public static void main(String[] args) {

        String[] arr = { "CSE01A", "ECE02B", "MECH03C" };

        System.out.println(getCourses(Lists.newArrayList(arr)));
        System.out.println(getGrades(Lists.newArrayList(arr)));

    }
}

Output:

CSE01, ECE02, MECH03
A, B, C

I have a feeling, though, that this is way over the top for what might be a simple homework assignment on iterating through arrays and string manipulation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM