3 Replies Latest reply: Apr 30, 2009 10:33 AM by 800303 RSS

    Problem related to String

    807588
      My input is "LastName1, FirstName1 (-) | 1","15","15"

      And I want output as mentioned below.

      "LastName1","FirstName1","-","1","15","15"

      Can anyone please suggest me best way to do that or provide me some sample code.

      Thanks
        • 1. Re: Problem related to String
          800282
          Kanni wrote:
          My input is "LastName1, FirstName1 (-) | 1","15","15"

          And I want output as mentioned below.

          "LastName1","FirstName1","-","1","15","15"

          Can anyone please suggest me best way to do that or provide me some sample code.

          Thanks
          Sure:
          String output = input.replace("\"LastName1, FirstName1 (-) | 1\",\"15\",\"15\"", "\"LastName1\",\"FirstName1\",\"-\",\"1\",\"15\",\"15\"");
          • 2. Re: Problem related to String
            800303
            Have you looked at the split() method in the String class, it should do what you want.
            • 3. Re: Problem related to String
              800303
              Still not 100% sure of what you want to do but hey ho. ;-)

              So assuming that you have lines of similarly delimited text and want to make them more like CSV format here is an example of using split():
              // Convert "\"LastName1, FirstName1 (-) | 1\",\"15\",\"15\""
              // to "LastName1","FirstName1","-","1","15","15"
              String line = "\"LastName1, FirstName1 (-) | 1\",\"15\",\"15\"";
              String tokens[] = line.split("[\\\",\\ |\\(\\)]");
              String token = null;
              StringBuffer newLine = new StringBuffer();
              for (int i = 0; i < tokens.length; i++) {
                   token = tokens;
                   if (token.trim().length() > 0) {
                        newLine.append("\"");
                        newLine.append(token);
                        newLine.append("\",");
                   }
              }
              System.out.println("newLine: '" + newLine + "'");

              // If you don't want the trailing comma you could either not add it or trim it off at the end
              newLine.setCharAt(newLine.lastIndexOf(","), ' ');
              System.out.println("newLine: '" + newLine.toString().trim() + "'");

              {code}

              Hope this helps!