1

I have string b="Name=Paul Roberts|Telephone=|Address=|City=LA"; I have been trying all day to get the output Attribute-Value pairs without equal and pipes signs. I have more then 4 results but this is what I want to achieve: Output (separate each pair because I have to put those two values into the fields of some table):

Name
Paul Roberts 

Telephone

Address

City
LA

So you can notice that VALUE can be null(empty).

I tried with SUBSTRING (maybe there is better way) but getting wrong results:

static String b="Name=Paul Roberts|Telephone=|Address=|City=LA";   

public static void main(String[] args) {

    System.out.println("b="+b);
    String match = "=";

    int i =0;
    while((i=(b.indexOf(match,i)+1))>0)
    { 
    String c=b.substring(0,i-1);
    String d=b.substring(i);
    String match2="|";
    int k=b.indexOf(match2);
    System.out.println("Attribute="+c);

    int j=d.indexOf(match2);
    if (j>-1)
    {
   String e=d.substring(0,j);
   System.out.println("Value="+e);
    }
    if (k>-1)
    {
    b=b.substring(k+1,b.length());
    }
    }
}

I am close to the correct result but this is what I am getting:

b=Name=Paul Roberts|Telephone=|Address=|City=LA
Attribute=Name
Value=Paul Roberts
Attribute=Telephone
Value=
Attribute=Address=|City

So you can notice that last row is not correct and I am missing two rows. Also is this with SUBSTRING most efficient way?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
ja jaaaa
  • 115
  • 4
  • 15

2 Answers2

3

Splitting the string makes this easier:

public static void main(String[] args) {
  String b="Name=Paul Roberts|Telephone=|Address=|City=LA";

  for (String s : b.split("\\|")) {
    String[] pair = s.split("=");

    String attribute = pair[0];
    String value = ((pair.length > 1) ? pair[1] : "");

    System.out.println("Attribute=" + attribute);
    System.out.println("Value=" + value);
    System.out.println();
  }
}

Output:

Attribute=Name
Value=Paul Roberts

Attribute=Telephone
Value=

Attribute=Address
Value=

Attribute=City
Value=LA
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
0

Very basic way to do this would be

    String b="Name=Paul Roberts|Telephone=|Address=|City=LA"; 
    b = b.replace("\"", "");
    b = b.replace("|", "\n");
    b = b.replace("=", "\n");
    System.out.println(b);

output is

Name
Paul Roberts
Telephone

Address

City
LA

Again it would be even better if you used StringBuffer for it rather than directly operating on Strings.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • Thank you for help but this is not what I want... I must get result in two separate String fields because both Attribute and Value I must insert in one row in two fields of additional table – ja jaaaa Jun 01 '14 at 07:19
  • Then now you can easily split using `\n` and use it the way you want. – Aniket Thakur Jun 01 '14 at 07:20