Parse a String to boolean

How do you parse a String to boolean, isn't like this? I get this inconertible types error, that require boolean
boolean all = (boolean)tokens.nextToken();
Thanks!

What string means true, and what string means false? The string "true" or "false"? In that case, you can simply use the Boolean.valueOf(String) method:
public static Boolean valueOf(String s)
    Returns a Boolean with a value represented by the specified String. The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
    Example: Boolean.valueOf("True") returns true.
    Example: Boolean.valueOf("yes") returns false.
    Parameters:
        s - a string.
    Returns:
        the Boolean value represented by the string.Otherwise, you can use something like:
  boolean b = string.equals("true");or if string can be null to also mean false:
  boolean b = "true".equals(string);

Similar Messages

  • String to boolean. Help needed.

    Hello ppl. Im here concerning my method for deleting files. I've got a bit of a difficulty....
    The method returns a String, becuase if an exception occurs it will return it, however if no exception occurs it returns true, as a String tho:
    return "true";
    Is there anyway to parse a string to a boolean value inside the method? or the invoking method?
    Method:
    public String delFile(String file){
    String error = null;
    File f = null;
    if(file!=null){
    try {
    f = new File(file);
    f.delete();
    } catch(SecurityException se){
    error = se.getMessage();
    if(error!=null) return error;
    return "true";
    Help appreciated. Thanks.

    Can I implement the custom exception method in the
    same class as the delFile() method?I think you got me wrong. You could do it like this:
    (1) Define your special exception class, which should
    be defined in a seperate file ("MyFileException.java")
    package myFileHandlingPackage;
    import java.io.*;
    public class MyFileException extends Exception{
    public final static int FILE_NOT_FOUND = 0;
    public final static int FILE_NAME_NULL = 1;
    public final static int NO_DELETION_PERMISSION = 2;
    private final static String[] messages;
    static{
       messages[] = new String[3];
       messages[0] = "The specified file could be found";
       messages[1] = "The file name was not specified";
       messages[2] = "You have no permission to delete the file";
    private int errorCode = -1;
    private File errorFile;
    public MyFileException(){
       super();
    public MyFileException(String msg){
       super(msg);
    public MyFileException(int errorCode, File errFile, String msg){
       MyFileException(msg);
       this.errorCode = errorCode;
       this.errorFile = errFile;
    public String getNiceMessage(){
       String niceMsg = "";
       if(errorCode != -1 && errorCode < 3){
         niceMsg += messages[errorCode];
         niceMsg += " ";
         niceMsg += errFile.getName();
       return niceMsg;
    }(2) import this class in your JSP and in the file you defined your
    delFile() method.
    (3) now you can use a catch(MyFileException mfe){...} in your JSP
    Hope that helps
    Adrian

  • Help regarding parsing the string

    I wanted to display diffrent colored strings in the Textarea which is not possible. But from somewhere I came to know that it is possible by parsing the strings comming frm various sources and then display them with diffrent colors. can anyone help me out regarding this. The format is something like:
    &x100100100This is a colored string!&n
    the &x100100100 means that the text after it should use RGB value of 100,100,100. &n meant that the colors should stop and return to default.
    Well... this makes the client need to parse strings and set colors etc
    Can anyone explain me with some small code without using the swing class. thanks in advance.

    Here is my code I am trying to do...Pls see to it and tell me the mistake....
    import java.net.*;
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    import java.util.*;
    import java.lang.*;
    public class client extends Applet
         //implements KeyListener
              TextArea display;
              //TextField send;
              TextArea send;
              Label status;
              Color color;
              mypanel p1;
              boolean connected=false;
              private Socket sock;
               protected BufferedReader instream;
              private DataOutputStream out;
              private String IP;
              private int port;
              Thread reader;
              private String fontName;
              private int fontSize;
              private String company;
              private String userName;
              private String userID;
              private String compName;
         public void start()
                   String param;
                   String mStr ;
                   IP=getParameter("IP");
                   userID=getParameter("userID");
                   userName=getParameter("userName");
                   fontName=getParameter("fontName");
                   company=getParameter("company");
                   mStr=userID+"#"+userName+"#US#"+company+"#1#A";
                   param=getParameter("fontSize");
                   try{
                        if (param!=null)
                             fontSize=Integer.parseInt(param);
                        else
                             fontSize=0;
                        } catch (NumberFormatException e){
                             fontSize=-1;                    
                   param=getParameter("port");
                   try{
                        if (param!=null)
                             port=Integer.parseInt(param);
                        else
                             port=2;
                        } catch (NumberFormatException e){
                             port=-1;     
                        //display.append(sock.getURL());
                        connect(IP,port,mStr);
         public void init()
                   setBackground(Color.white);
                   //color = new Color(221,240,255);
                   setForeground(Color.black);
                   p1=new mypanel();
                   add(p1);
                   reader = new readMessage(this);
                reader.setPriority(1);
                   //send.addKeyListener(this);
         public void paint(Graphics g){
              String s;
              double p;
              int i;
              //status.setBackground(Color.blue);
              g.setColor(color);
              display.setEditable(false);
              status.setForeground(Color.black);
              display.setBackground(Color.white);
              p1.cmdSend.setBackground(Color.white);
              p1.cmdSend.setForeground(Color.black);
              display.setFont(new Font("Arial", Font.PLAIN, 11));
              //status.setBackground(Color.blue);
              display.setForeground(Color.blue);
         public void connect(String host,int p,String mStr)
               try{
                   sock=new Socket(host,p);
                   instream = new BufferedReader( new InputStreamReader(sock.getInputStream()));
                   out = new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()));
                   out.writeBytes(mStr);
                   connected=true;
                   out.flush();
                   reader.start();
                   setStatus("You are Connected Successfully. ");
                   display.append("Welcome to "+company+" chat . A Customer Support Executive will assist you shortly.\n");
                   catch (UnknownHostException a) {
                             connected=false;
                             p1.cmdSend.setEnabled(false);
                             send.setEditable(false);
                             display.append(company+" live support service fails due to some technical reason.");
                            //status.setText("Intelecorp Live Suport service fails due to some technical reasions.");
                   catch (IOException b) {
                             connected=false;
                             p1.cmdSend.setEnabled(false);
                             send.setEditable(false);
                             display.append(company+" live support service fails due to some technical reason.");
                            //status.setText("Intelecorp Live Suport service fails due to some technical reasions.");
                   catch (SecurityException c ) {
                        connected = false;
                        display.append("Error");
              public void setStatus(String mstr)
                   status.setText(mstr);
              public boolean action (Event e, Object arg)
                   if(e.target instanceof Button)
                        if (e.target==p1.cmdSend)
                             sendMessage(send.getText());
                             send.setText("");
                             return true;
                   return false;
    public boolean keyUp(Event e, int key)
            if(key==Event.ENTER)
                   sendMessage(send.getText());
                  send.setText("");
                   return true;
            return false;
         public void keyPressed(KeyEvent e)
              switch (e.getKeyCode()) {
                   case KeyEvent.VK_ENTER:
                        sendMessage(send.getText());
                        send.setText("");
                        break;
                   default:
                        break;
              return ;
         public void keyReleased(KeyEvent e) {} ;
         public void keyTyped(KeyEvent e) {} ;
         public void sendMessage(String mStr)
                   int mflag;
                   try{
                        mflag=mStr.lastIndexOf('\n');
                        mStr.trim();
                        if ((connected==true) && (mStr.length()>0))
                             if (mflag<0)
                                  mStr=mStr+"\n";
                             display.append(userName+" : "+"&x100100100"+mStr+"!&n");
                             out.writeBytes(mStr);
                             out.flush();
                             send.setText("");
                   }catch (IOException e){
                             connected=false;
                             p1.cmdSend.setEnabled(false);
                             send.setEditable(false);
                             display.append("Unable to send the message, you may be disconnected from the server.");
                             //status.setText("Unable to send the message, you may disconnected from the server.");
    public void destroy(){
              try{
                   sock.close();
                   }catch (IOException e){
                             status.setText(e.toString());
    class readMessage extends Thread{
              client mClient;
              private String mStr;
             public readMessage(client c){
                        super("Client Reader");
                        this.mClient = c;
    public void run()
              mStr=null;
         try{
                        if (connected==true)
                             while(true)
                               mStr = instream.readLine();
                               display.append("&x200200200"+mStr+"!&n"+"\n");
                               //display.setText(display.getText()+"\n"+mStr);
                                    if (mStr==null)
                                  break;
              }catch (IOException e){
                             connected=false;
                             p1.cmdSend.setEnabled(false);
                             send.setEditable(false);
                             display.append("Unable to read the messages, you may be disconnected from the server.");
                             //status.setText("Unable to read the messages, you may disconnected from the server.");
    class mypanel extends Panel 
                   Label l1,l2,l3;
                   Button cmdSend;
                   mypanel()
                        setLayout(new BorderLayout());
                        add("North",display=new TextArea("",12,50,TextArea.SCROLLBARS_VERTICAL_ONLY));
                        add("West",send=new TextArea("",2,50,TextArea.SCROLLBARS_VERTICAL_ONLY));
                        //add("West",send=new TextField());
                        add("East",cmdSend=new Button("  Send  "));
                        add("South",status=new Label(""));
    }

  • Parsing a string using StringTokenizer

    Hi,
    I want to parse a string such as
    String input = ab{cd}:"abc""de"{
    and the extracted tokens should be as follows
    ab
    cd
    "abc""de"
    As a result, I used the StringTokenizer class with deilmeter {,},:
    StringTokenizer tokenizer = new StringTokenizer(input,"{}:", true);
    In this was, I can separate the tokens and also can get the delimeters. The problem is I don't know how to parse the string that has double quote on it. If a single quote " is taken as a delimeter then
    ", abc, ",", de," all of them will be taken as a separate token. My intention is to get the whole string inside the double quote as a token including the quotes on it. Moreover, if there is any escape character "", it should be also included in the token. Help please.
    Thanks

    A bit of a "sticky tape"-solution...
    import java.util.StringTokenizer;
    public class Test {
        public static void main(String[] args) {
            String input = "ab{cd}:\"abc\"\"de\"";
            StringTokenizer st = new StringTokenizer(input, "{}:", true);
            while(st.hasMoreTokens()) {
            String token = st.nextToken();
            if(token.startsWith("\"") && token.endsWith("\"")) {
            token = token.substring(1,token.length()-1);
                System.out.println(token);
    }

  • How to Parse a string into an XML DOM ?

    Hi,
    I want to parse a String into an XML DOM. Not able to locate any parser which supports that. Any pointers to this?

    Download Xerces from xml.apache.org. Place the relevant JAR's on your classpath. Here is sample code to get a DOM document reference.
    - Saish
    public final class DomParser extends Object {
         // Class Variables //
         private static final DocumentBuilder builder;
         private static final String JAXP_SCHEMA_LANGUAGE =
             "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
         /** W3C schema definitions */
         private static final String W3C_XML_SCHEMA =
             "http://www.w3.org/2001/XMLSchema";
         // Constructors //
         static {
              try {
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   factory.setNamespaceAware(true);
                   factory.setValidating(true);
                   factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
                   builder = factory.newDocumentBuilder();
                   builder.setErrorHandler(new ErrorHandler() {
                       public void warning(SAXParseException e) throws SAXException {
                           System.err.println("[warning] "+e.getMessage());
                       public void error(SAXParseException e) throws SAXException {
                           System.err.println("[error] "+e.getMessage());
                       public void fatalError(SAXParseException e) throws SAXException {
                           System.err.println("[fatal error] "+e.getMessage());
                           throw new XmlParsingError("Fatal validation error", e);
              catch (ParserConfigurationException fatal) {
                   throw new ConfigurationError("Unable to create XML DOM document parser", fatal);
              catch (FactoryConfigurationError fatal) {
                   throw new ConfigurationError("Unable to create XML DOM document factory", fatal);
         private DomParser() {
              super();
         // Public Methods //
         public static final Document newDocument() {
              return builder.newDocument();
         public static final Document parseDocument(final InputStream in) {
              try {
                   return builder.parse(in);
              catch (SAXException e) {
                   throw new XmlParsingError("SAX exception during parsing.  Document is not well-formed or contains " +
                        "illegal characters", e);
              catch (IOException e) {
                   throw new XmlParsingError("Encountered I/O exception during parsing", e);
    }- Saish

  • Parsing formatted String to Int

    How can I parse formatted string to Integer ?
    I have a formated string like this $900,000 and I need to convert it to 900000 so I could do calculations with it.
    I tried something like this
    NumberFormat nf = NumberFormat.getIntegerInstance(request.getLocale());
    ttlMargin=nf.parse(screenVal);I got this exception
    "java.lang.NumberFormatException: For input string: "$1,050,000""

    I am working on the JSP file that provides
    margins,sales etc. I am reading this data off the
    screen where it is beeing displayed according to the
    accounting practices.
    That's why I get it as a formatted string and why I
    am trying covert that string to the numberScreen-scraping is a problematic, bad design. It sounds like what you really want is to call a web service which returns its results as data that a program can understand (XML, for example), not HTML (which is meant more for humans to read). I know, you probably can't change the design at this point... just food for thought. In the meantime, you'll probably have to manually parse those strings yourself by stripping out the '$' and ',' characters and then use parseInt on the result.

  • How to parse a string containing xml data

    Hi,
    Is it possible to parse a string containing xml data into a array list?
    my string contains xml data as <blood_group>
         <choice id ='1' value='A +ve'/>
         <choice id ='2' value='B +ve'/>
             <choice id ='3' value='O +ve'/>
    </blood_group>how can i get "value" into array list?

    There are lot of Java XML parsing API's available, e.g. JAXP, DOM4J, JXPath, etc.
    Of course you can also write it yourself. Look which methods the String API offers you, e.g. substring and *indexOf.                                                                                                                                                                                                                                                                                                                                                                                                               

  • Passing / parsing XML String IN / OUT from PL / SQL package

    Hello, People !
    I am wondering where can I find exact info (with code sample) about following :
    We use Oracle 8.1.6 and 8.1.7. I need to pass an XML String (could be from VARCHAR2 to CLOB) from VB 6.0 to PL/SQL package. Then I need to use built in PL/SQL XML parser to parse given string (could be large hierarchy of nodes)
    and the return some kind of cursor thru I can loop and insert data into
    different db Tables. (The return value may have complex parent/child data relationship - so I am not sure If this should be a cursor)
    I looked online many site for related info - can't find what I am looking
    for - seems like should be a common question.
    Thanx a lot !

    Hello, People !
    I am wondering where can I find exact info (with code sample) about following :
    We use Oracle 8.1.6 and 8.1.7. I need to pass an XML String (could be from VARCHAR2 to CLOB) from VB 6.0 to PL/SQL package. Then I need to use built in PL/SQL XML parser to parse given string (could be large hierarchy of nodes)
    and the return some kind of cursor thru I can loop and insert data into
    different db Tables. (The return value may have complex parent/child data relationship - so I am not sure If this should be a cursor)
    I looked online many site for related info - can't find what I am looking
    for - seems like should be a common question.
    Thanx a lot !

  • How can I convert a String into boolean?

    I am facing difficulty in converting String into boolean.
    For example, I have a few variable which i need user to input yes or no as the answer. But I uses string instead. Is there a way which i can ask them to input boolean directly?
    Please advise...
    credit = JOptionPane.showInputDialog("Enter Yes or No for Credit Satisfactory : ");
    System.out.println("The answer for Credit Satisfactory : "+credit);
    e_invtry=JOptionPane.showInputDialog("Enter Yes or No for inventry level");
    System.out.println("The answer for Quantity Order : "+e_invtry);
    Message was edited by:
    SummerCool

    Thanks...but I don't get it....I tried to use your
    suggestion but i got the message that " cannot find
    symbol method
    showConfirmDialog(java.lang.String,int)" ???
    Please advise.
    The code I use was :
    int credit = JOptionPane.showConfirmDialog("Enter Yes
    or No for credit satisfactory",
    JOptionPane.YES_NO_OPTION);Well that was not the example I gave you.
    JOptionPane has no method showConfirmDialog that receives a String and an int (exactly what the error message is telling you).
    What was wrong with the version I showed you?

  • How to parse a string in CVP 7.0(1). Is there a built-in java class, other?

    Hi,
    I need to parse,in CVP 7.0(1), the BAAccountNumber variable passed by the ICM dialer.  Is there a built-in java class or other function that would help me do this?
    Our BAAccountNumber variable looks something like this: 321|XXX12345678|1901|M. In IP IVR I use the "Get ICM Data" object to read the BAAccountNumber variable from ICM and then I use the "token index" feature to parse the variable (picture below).
    Alternately, IP IVR also has a Java class that allows me to do this; the class is "java.lang.String" and the method is "public int indexOf(String,int)"
    Is there something equivalent in CVP 7.0(1)?
    thanks

    Thanks again for your help.  This is what I ended up doing:
    This configurable action element takes a string seperated by two "|" (123|123456789|12)
    and returns 3 string variables.
    you can add more output variables by adding to the Setting array below.
    // These classes are used by custom configurable elements.
    import com.audium.server.session.ActionElementData;
    import com.audium.server.voiceElement.ActionElementBase;
    import com.audium.server.voiceElement.ElementData;
    import com.audium.server.voiceElement.ElementException;
    import com.audium.server.voiceElement.ElementInterface;
    import com.audium.server.voiceElement.Setting;
    import com.audium.server.xml.ActionElementConfig;
    public class SOMENAMEHERE extends ActionElementBase implements ElementInterface
         * This method is run when the action is visited. From the ActionElementData
         * object, the configuration can be obtained.
        public void doAction(String name, ActionElementData actionData) throws ElementException
            try {
                // Get the configuration
                ActionElementConfig config = actionData.getActionElementConfig();
                //now retrieve each setting value using its 'real' name as defined in the getSettings method above
                //each setting is returned as a String type, but can be converted.
                String input = config.getSettingValue("input",actionData);
                String resultType = config.getSettingValue("resultType",actionData);
                String resultEntityID = config.getSettingValue("resultEntityID",actionData);
                String resultMemberID = config.getSettingValue("resultMemberID",actionData);
                String resultTFNType = config.getSettingValue("resultTFNType",actionData);
                //get the substring
                //String sub = input.substring(startPos,startPos+numChars);
                String[] BAAcctresults = input.split("\\|");
                //Now store the substring into either Element or Session data as requested
                //and store it into the variable name requested by the Studio developer
                if(resultType.equals("Element")){
                    actionData.setElementData(resultEntityID,BAAcctresults[0]);
                    actionData.setElementData(resultMemberID,BAAcctresults[1]);
                    actionData.setElementData(resultTFNType,BAAcctresults[2]);
                } else {
                    actionData.setSessionData(resultEntityID,BAAcctresults[0]);
                    actionData.setSessionData(resultMemberID,BAAcctresults[1]);
                    actionData.setSessionData(resultTFNType,BAAcctresults[2]);
                actionData.setElementData("status","success");
            } catch (Exception e) {
                //If anything goes wrong, create Element data 'status' with the value 'failure'
                //and return an empty string into the variable requested by the caller
                e.printStackTrace();
                actionData.setElementData("status","failure");
        public String getElementName()
            return "MEDDOC PARSER";
        public String getDisplayFolderName()
            return "SSC Custom";
        public String getDescription()
            return "This class breaks down the BAAccountNumber";
        public Setting[] getSettings() throws ElementException
             //You must define the number of settings here
             Setting[] settingArray = new Setting[5];
              //each setting must specify: real name, display name, description,
              //is it required?, can it only appear once?, does it allow substitution?,
              //and the type of entry allowed
            settingArray[0] = new Setting("input", "Original String",
                       "This is the string from which to grab a substring.",
                       true,   // It is required
                       true,   // It appears only once
                       true,   // It allows substitution
                       Setting.STRING);
            settingArray[1] = new Setting("resultType", "Result Type",
                    "Choose where to store result \n" +
                    "into Element or Session data",
                    true,   // It is required
                    true,   // It appears only once
                    false,  // It does NOT allow substitution
                    new String[]{"Element","Session"});//pull-down menu
            settingArray[1].setDefaultValue("Session");
            settingArray[2] = new Setting("resultEntityID", "EntityID",
              "Name of variable to hold the result.",
              true,   // It is required
              true,   // It appears only once
              true,   // It allows substitution
              Setting.STRING);  
            settingArray[2].setDefaultValue("EntityID");
            settingArray[3] = new Setting("resultMemberID", "MemberID",
                    "Name of variable to hold the result.",
                    true,   // It is required
                    true,   // It appears only once
                    true,   // It allows substitution
                    Setting.STRING);  
            settingArray[3].setDefaultValue("MemberID");
            settingArray[4] = new Setting("resultTFNType", "TFNType",
                      "Name of variable to hold the result.",
                      true,   // It is required
                      true,   // It appears only once
                      true,   // It allows substitution
                      Setting.STRING);  
            settingArray[4].setDefaultValue("TFNType");    
    return settingArray;
        public ElementData[] getElementData() throws ElementException
            return null;

  • Date contructor deprecation : Parsing a String to Date

    Hi All,
    In Java 1.5 the Date() constructor Date(String s) is deprecated. As per the API Documentation DateFormat.Parse() method is used.
    The following code from Java 1.4 version has to be upgraded to Java 1.5.
    Existing Code:
    Date dDate = new Date(sDate);
    Modified Code:
    DateFormat df = DateFormat.getDateInstance();
    Date dDate = df.parse(sDate);
    Here the DateFormat accepts a default formatting style as "Feb 01, 2007" and parses the String.
    If the String sDate belongs to any other formatting style such as "01 Feb, 2007" or "01 Feb, 07" the code piece throws unparsable date error.
    Please give your thougts on this issue to parse the string of any format..
    Thanks,
    Rajesh.

    Hi All,
    In Java 1.5 the Date() constructor Date(String s) is
    deprecated. As per the API Documentation
    DateFormat.Parse() method is used.
    The following code from Java 1.4 version has to be
    upgraded to Java 1.5.
    Existing Code:
    Date dDate = new Date(sDate);
    Modified Code:
    DateFormat df = DateFormat.getDateInstance();
    Date dDate = df.parse(sDate);
    Here the DateFormat accepts a default formatting
    style as "Feb 01, 2007" and parses the String.
    If the String sDate belongs to any other formatting
    style such as "01 Feb, 2007" or "01 Feb, 07" the code
    piece throws unparsable date error.
    Please give your thougts on this issue to parse the
    string of any format..You can't. What date is this: "08/04/24"? 8 April, 1924? 4 August, 2024?
    >
    Thanks,
    Rajesh.

  • Parsing a string in a sproc

    I have a Java class that calls a stored proc and passes a stringbuffer object to it. The sproc should parse the string to retrieve the different ids that are concatenated in the stringbuffer and for each id retrieve a row from a table and in the end return a cursor containing the returned rows.Can anyone help me out with the parsing logic for a pipe delimited string.
    Tathagata

    This might help you. If you want to handle the cursor in java, then convert the below into a function which returns the cursor.
    SQL> CREATE TABLE EMP(ENAME VARCHAR2(100),ENO NUMBER(5),DEPT NUMBER(5))
      2  /
    Table created.
    SQL> INSERT INTO EMP VALUES('SCOTT',1,2);
    1 row created.
    SQL> INSERT INTO EMP VALUES('TIGER',2,5);
    1 row created.
    SQL> INSERT INTO EMP VALUES('THOMAS',3,10);
    1 row created.
    SQL> INSERT INTO EMP VALUES('PETER',4,10);
    1 row created.
    SQL> INSERT INTO EMP VALUES('HARRY',7,10);
    1 row created.
    SQL> CREATE OR REPLACE PROCEDURE PARSE_STRING(STR VARCHAR2)
      2  AS
      3  TYPE EmpCurTyp IS REF CURSOR;
      4  emp_cv EmpCurTyp;
      5  STRING VARCHAR2(1000);
      6  type emp_t is table of emp%rowtype;
      7  emp_tab emp_t;
      8  BEGIN
      9  STRING := REPLACE(STR,'|',',');
    10  OPEN emp_cv FOR 'SELECT ENAME,ENO,DEPT FROM EMP WHERE ENO IN('||string||')';
    11  FETCH emp_cv BULK COLLECT INTO EMP_TAB;
    12  CLOSE emp_cv;
    13  FOR I IN 1..EMP_TAB.LAST
    14  LOOP
    15  DBMS_OUTPUT.PUT_LINE(EMP_TAB(I).ENAME);
    16  END LOOP;
    17  EXCEPTION
    18  WHEN OTHERS THEN
    19  DBMS_OUTPUT.PUT_LINE('ERROR OCCURED ' || SQLCODE ||' ' || SQLERRM);
    20  END;
    21  /
    Procedure created.
    SQL> set serveroutput on;
    SQL> BEGIN
      2  PARSE_STRING('1|2|3|4');
      3  END;
      4  /
    SCOTT
    TIGER
    THOMAS
    PETER
    PL/SQL procedure successfully completed.
    SQL>Regards,
    Mohana

  • Parsing a string in a given order

    Hi All,
    I want to parse a string and rank it in a given order.
    Eg : i have a string as 'A | B | C | D'. I would like to parse this string and give a rank in order.
    It should appear as below.
    Parsed string order
    D 1
    C 2
    B 3
    A 4
    Any help is greatly appreciated..

    A database version would help us providing you with a relevant solution.
    Starting with 10g, you can do :
    SQL> var my_str varchar2(30)
    SQL> exec :my_str := 'A|B|C|D'
    PL/SQL procedure successfully completed
    SQL> select item
      2       , row_number() over(order by item desc) as rank
      3  from (
      4    select regexp_substr(:my_str,'[^|]+',1,level) as item
      5    from dual
      6    connect by level <= length(regexp_replace(:my_str,'[^|]+')) + 1
      7  );
    ITEM                    RANK
    D                          1
    C                          2
    B                          3
    A                          4
    In 11.2 :
    SQL> select *
      2  from xmltable(
      3       'for $i in ora:tokenize($str,"\|") order by $i descending return $i'
      4       passing 'A|B|C|D' as "str"
      5       columns item varchar2(10) path '.'
      6             , rank for ordinality
      7       )
      8  ;
    ITEM             RANK
    D                   1
    C                   2
    B                   3
    A                   4
    Edited by: odie_63 on 11 janv. 2012 12:56 - added 11.2

  • Parsing a string in PL/SQL?

    I am parsing a string in PL/SQL and at a certain point(Length 45) of the string I would like to add a carriage return (Chr(10)), then continue with the string at that point and then again if the string is greater than Length 45 add a carriage return.
    I program in Powerbuilder and have figured it out, but I have a problem when trying to add a carriage return at a certain point in the string in PL/SQL. There is the REPLACE(), but that will replace everything, but I only want to add it at that certain point of the string. With the PB function I can add the carriage return at a certain point, see code:
    Li_pos = PosA( Ps_data, '*')
    DO WHILE Li_pos > 0
    ll_length = Li_pos - ll_old_pos
    IF ll_length > 45 THEN
    ll_old_pos = Li_pos
    Ps_data = ReplaceA( Ps_data, Li_Pos, 1, ls_carriage_rtn) **This function gives me the ability to add a carriage return at a certain point in the string. **
    Li_pos = PosA( Ps_data, '*', Li_pos + 1 + ls_carriage_rtn)
    ELSE
    Li_pos = PosA( Ps_data, '*', Li_pos + 1)
    END IF
    LOOP
    I have incorporated the same logic in PL/SQL but I am looking for something similar to the ReplaceA function in PB, that will replace at a certain point in a string. I use an '*' as a placeholder and measure the length. Below is the PL/SQL code:
    t_pos NUMBER;
    t_old_pos NUMBER;
    t_length NUMBER;
    BEGIN
    t_old_pos := 0;
    t_pos := INSTR(in_model_list, '*');
    WHILE t_pos > 0 LOOP
    t_length := t_pos - t_old_pos; -- This looks at current position minus the old position, measures the length
    IF t_length > 45 THEN
    t_old_pos := t_pos;
    *** add that carriage return
    t_pos := INSTR(in_model_list, '*', t_pos + 1 + Chr(10)); -- get the new position
    NULL;
    ELSE
    t_pos := INSTR(in_model_list, '*', t_pos + 1);
    END IF;
    NULL;
    END LOOP;
    Here is the data, what it looks like: William 112,* 500-A,* 500-U,* 520,* 560-A,* 560-E,* 680-E,* 680-F,* 680-V*
    Any help would be much appreciated.
    Thank you,
    William
    Edited by: William on Feb 28, 2012 6:56 AM

    Frank Kulash wrote:
    [example]I played with your example and came to this:SQL> WITH my_string AS
      2         (SELECT '1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'
      3                   AS mt
      4            FROM DUAL)
      5     ,  line_length AS
      6         (SELECT 13 AS chars
      7            FROM DUAL)
      8      SELECT LISTAGG (REGEXP_SUBSTR (mt,'(.{'|| line_length.chars|| '})', 1, LEVEL),chr(10)) WITHIN GROUP (ORDER BY LEVEL)
      9             ||chr(10)
    10             ||substr(mt,-mod(LENGTH (mt),line_length.chars)) as wrapped_text
    11        FROM my_string
    12        CROSS JOIN line_length
    13  CONNECT BY LEVEL < 1+LENGTH (mt) ;
    WRAPPED_TEXT
    1234567890123
    4567890123456
    7890123456789
    0123456789012
    3456789012345
    6789012345678
    9012345678901
    2345678901234
    5678901234567
    8901234567890
    1234567890123
    WRAPPED_TEXT
    4567890123456
    7890
    SQL>*[Edit]* annotated that this is 11g only...
    Edited by: T.PD on 29.02.2012 21:17

  • Problems parsing a string

    Hi,
    I'm having a problem with parsing a string. Basically, I want to take a string for example: "TomWentToTheShop" and divide it into a coherent sentence (Tom went to the shop).
    I've started the code by breaking the string into a char array, and if the character is a capital then store the index in the array and then do a substring.
    But I don't think this is the best way to solve the problem, if anyone has any ideas it would be greatly appreciated.
    thanks.
    char[] charRequestTypeArray = string.toCharArray();
    for (int i = 1; i < (charRequestTypeArray.length -1); i++) {
    char c = charRequestTypeArray;
    if (Character.isUpperCase(c)) {
    Arrays.fill(storeCapitalIndex, i);
    else{
    Arrays.fill(storeNonCapitalIndex, i);

            String s = "TomWentToTheShop";
            System.out.println(s.charAt(0) + s.substring(1).replaceAll("((?<!^)[A-Z])", " $1").toLowerCase());or even just        System.out.println(s.charAt(0) + s.substring(1).replaceAll("([A-Z])", " $1").toLowerCase());Edited by: sabre150 on Nov 11, 2007 9:40 PM

Maybe you are looking for