0

I have a string in java:

String text = "A, B, C, D, ";

How I can to get "A, B, C and D"?

I have "A, B, C, D" as well: text.substring(0, text.lastIndexOf(",")), but how do I get the result I want?

Thanks!!!

Ali
  • 56,466
  • 29
  • 168
  • 265
victorpacheco3107
  • 822
  • 3
  • 10
  • 32

6 Answers6

1

How about something like

text = text.replaceAll(", (\\w+), $", " and $1");

replaceAll uses regex as first parameter and can use parts matched by this regex in replacement via $x where x refers to part matched with group number x (to put it shortly groups are parts or regex from parenthesis).

So this regex will match , oneOrMoreCharacters, which is right before the end of string which in regex can be represented with $.

DEMO:

System.out.println("A, B, C, D, ".replaceAll(", (\\w+), $", " and $1"));

output: A, B, C and D


EDIT

If your D part can also contain non alphanumeric characters then instead of \\w use [^,] which represents all characters except ,. So try with

text = text.replaceAll(", ([^,]+), $", " and $1");
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • Your code work in this example, but when the elments contains space this not work, example: "First word, second word, other word, etc, "..replaceAll(", (\\w+), $", " and $1") give as result the same input. Thanks for your response. – victorpacheco3107 Mar 13 '14 at 20:47
  • @victorpacheco3107 then instead of `\\w` which represents only alphanumeric characters you can use `[^,]` which represents all characters except comma. – Pshemo Mar 13 '14 at 20:48
  • @victorpacheco3107 Could you test my updated answer? – Pshemo Mar 13 '14 at 20:51
  • @victorpacheco3107 Glad you like it :) – Pshemo Mar 13 '14 at 21:58
0
"A, B, C, D, ".replace(", D, ", " and D");
DmitryKanunnikoff
  • 2,226
  • 2
  • 22
  • 35
0

You could do the following:

  1. Remove the last "," So you will be left with A, B, C, D
  2. Replace the last "," with " and " The result is A, B, C and D.

You can do this using StringBuilder:

String myStr = "A, B, C, D,";
StringBuilder builder = new StringBuilder(myStr);
builder.replace(builder.lastIndexOf(","), builder.lastIndexOf(",")+1, "");
builder.replace(builder.lastIndexOf(","), builder.lastIndexOf(",")+1, " and ");
String result = builder.toString();

System.out.println(result);//Should print A, B, C and D

I have not tested this code. But you get the idea.

Susie
  • 5,038
  • 10
  • 53
  • 74
0
String text = "A, B, C, D, ";
String[] split=text.split(",");
String ans="";
for(int i=0;i<split.length;i++){
    if(i==split.length-2){
        ans+= "and "+ split[i].replace(" ","");
        break;
    }
    if(i>0){
      ans+=", ";
    }
    ans+=split[i];
}

System.out.println(ans); // what you wanted
Dima
  • 8,586
  • 4
  • 28
  • 57
  • As OP claims real values under `D` can be even words separated with space so this solution will generate `A, B, Cand word1word2word3` for input as `"A, B, C, word1 word2 word3, "`. – Pshemo Mar 13 '14 at 22:15
  • this code is not splitted by spaces. read the answer before you write comments. – Dima Mar 14 '14 at 14:34
0

It seems like you are using code like

List<String> list = Arrays.asList("A", "B", "C", "D");
String text = "";
for (String token : list) {
    text += token + ", ";
}
System.out.println(text);

to generate your text value.

Instead, write the first value. Then write everything but the last value. Then write the last value with the and prepended.

List<String> list = Arrays.asList("A", "B", "C", "D");
String text = "";
if (!list.isEmpty()) {
    text += list.get(0);
    for (int i = 1; i < list.size() - 1; i++) {
        text += ", " + list.get(i);
    }
    if (list.size() > 1)
        text += " and " + list.get(list.size() - 1);
}
System.out.println(text);

Obviously, use a StringBuilder if appropriate. The above prints

A, B, C and D

The beauty of this is that it works with any number of values, doing the least possible number of checks for lengths and tokens remaining. With a single element, it would print only that value

A

With two elements (A and B), it would print

A and B

And so on.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

You could try something like the following:

String text = "A, B, C, D, ";
String[] a=text.split(",");
int i=a.length-1;
    while(i>=0 && (a[i]==null || a[i].trim().isEmpty()))
        i--;

System.out.println(a[i]);
John Kane
  • 4,383
  • 1
  • 24
  • 42