Suvonkar
Suvonkar

Reputation: 2460

Remove last set of value from a comma separated string in java

I wan to remove the last set of data from string using java. For example I have a string like A,B,C, and I want to remove ,C, and want to get the out put value like A,B . How is it possible in java? Please help.

Upvotes: 3

Views: 10095

Answers (8)

R.Akhlaghi
R.Akhlaghi

Reputation: 760

public string RemoveLastSepratorFromString(string input)
{
    string result = input;
    if (result.Length > 1)
    {
        result = input.Remove(input.Length - 1, 1);
    }
    
    return result;
}
        
// use from above method
string test = "1,2,3,"
string strResult = RemoveLastSepratorFromString(test);
//output --> 1,2,3

Upvotes: 0

Giorgos Dimtsas
Giorgos Dimtsas

Reputation: 12609

Another way to do this is using a 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 += ",";
    }
  }

Upvotes: 0

Ashish Patil
Ashish Patil

Reputation: 808

If full String.split() is not possible, the how about just scanning the string for comma and stop after reaching 2nd, without including it in final answer?

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());

Simple trick, but should be efficient.

In case you want last set of data removed, irrespective of how much you want to read, then start.substring(0, start.lastIndexOf(',', start.lastIndexOf(',')-1))

Upvotes: 0

Gopi
Gopi

Reputation: 10293

You can use regex to do this

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

prints

A,B

This simply erases the the 'second last comma followed by data followed by last comma'

Upvotes: 0

aioobe
aioobe

Reputation: 420951

Here is a fairly "robust" 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));
}

Output:

A,B
A
A,B
ABC,DEF,GHI

Upvotes: 4

T.J. Crowder
T.J. Crowder

Reputation: 1074168

You can use String#lastIndexOf to find the index of the second-to-last comma, and then String#substring to extract just the part before it. Since your sample data ends with a ",", you'll need to use the version of String#lastIndexOf that accepts a starting point and have it skip the last character (e.g., feed in the string's length minus 1).

I wasn't going to post actual code on the theory better to teach a man to fish, but as everyone else is:

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

Upvotes: 0

Peter DeWeese
Peter DeWeese

Reputation: 18333

Since there may be a trailing comma, something like this (using org.apache.commons.lang.StringUtils):

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

Upvotes: 2

Key
Key

Reputation: 7076

String start = "A,B,C,";
String result = start.subString(0, start.lastIndexOf(',', start.lastIndexOf(',') - 1));

Upvotes: 4

Related Questions