Remove last set of values ​​from comma separated string in java

I want to remove the last dataset from a row using java. For example, I have a type string A,B,C,, and I want to delete ,C,and want to get the value of out put, like A,B. How is this possible in java? Please, help.

+3
source share
7 answers
String start = "A,B,C,";
String result = start.subString(0, start.lastIndexOf(',', start.lastIndexOf(',') - 1));
+3
source

Here is a pretty "reliable" reg-exp solution:

Pattern p = Pattern.compile("((\\w,?)+),\\w+,?");

for (String test : new String[] {"A,B,C", "A,B", "A,B,C,",
                                 "ABC,DEF,GHI,JKL"}) {
    Matcher m = p.matcher(test);
    if (m.matches())
        System.out.println(m.group(1));
}

Conclusion:

A,B
A
A,B
ABC,DEF,GHI
+4
source

, - ( org.apache.commons.lang.StringUtils):

ArrayList<String> list = new ArrayList(Arrays.asList(myString.split()));
list.remove(list.length-1);
myString = StringUtils.join(list, ",");
+2

String#lastIndexOf - , String#substring, . ",", String#lastIndexOf, , (, length 1).

, , , :

String data = "A,B,C,";
String shortened = data.substring(0, data.lastIndexOf(',', data.length() - 2));
0

String.split() , 2-, ?

String start = "A,B";
StringBuilder result = new StringBuilder();
int count = 0;
for(char ch:start.toCharArray()) {
    if(ch == ',') {
        count++;
        if(count==2) {
            break;
        }
    }
    result.append(ch);
}
System.out.println("Result = "+result.toString());

, .

If you want to delete the last data set, no matter how much you want to read, then start.substring(0, start.lastIndexOf(',', start.lastIndexOf(',')-1))

0
source

You can use regex for this

String start = "A,B,C,";
String result = start.replaceAll(",[^,]*,$", "");
System.out.println(result);

prints

A,B

It just removes the "second last comma followed by data followed by the last comma"

0
source

Another way to do this is to use StringTokenizer:

  String input = "A,B,C,";
  StringTokenizer tokenizer = new StringTokenizer(input, ",");
  String output = new String();
  int tokenCount = tokenizer.countTokens();
  for (int i = 0; i < tokenCount - 1; i++) {
    output += tokenizer.nextToken();
    if (i < tokenCount - 1) {
      output += ",";
    }
  }
0
source

Source: https://habr.com/ru/post/1764677/


All Articles