How do I collapse " " in a java String?

Suppose I have a string say:
String s = "abcdef ghijkl mnop";
How do I treat this string so that
I get the resulting string as:
s1 = " abcdefghijklmnop";
Is there any method to do the same?

Thanks for the prompt reply ,but my question was how do I move the elements of the string which follow the spaces to replace the blank literals? for Instance
s = "I AM HAPPY";
after treatment gives
s = "IAMHAPPY";

Similar Messages

  • How many java String objects are created in string literal pool by executin

    How many java String objects are created in string literal pool by executing following five lines of code.
    String str = "Java";
    str = str.concat(" Beans ");
    str = str.trim();
    String str1 = "abc";
    String str2 = new String("abc").intern();
    Kindly explain thanks in advance
    Senthil

    virtuoso. wrote:
    jverd wrote:
    In Java all instances are kept on the heap. The "String literal pool" is no exception. It doesn't hold instances. It holds references to String objects on the heap.Um, no.
    The literal pool is part of the heap, and it holds String instances.
    [http://java.sun.com/docs/books/jvms/second_edition/html/Overview.doc.html#22972]
    [http://java.sun.com/docs/books/jvms/second_edition/html/ConstantPool.doc.html#67960]
    You're referring to the JVM. That's not Java.It's part of Java.
    There is nowhere in Java where it is correct to say "The string literal pool holds references, not String objects."

  • How do I get the proper UTF-8 NVARCHAR2 DB Value into a Java String?

    Hello, I have a mixed char 8.1.7 database with UTF-8 as my NLS
    charset. I used SQL Worksheet to enter test polish unicode
    characters 50309,50310... into an NVARCHAR2 column using
    insert...char(nnn using NCHAR_CS) and get the following result
    from DUMP(columnname,1016):
    Typ=1 Len=12 CharacterSet=UTF8:
    c4,85,c4,86,c4,87,c4,88,c4,89,c4,8a.
    Everything looks good.
    Now, how do I get them out into a Java String and verify that I
    have received the correct hex codes?
    I have tried:
    1. CHAR lChr = OracleResultSet.getCHAR(ColumnName, csUTF8); or
    and lChr.characterStreamValue();
    2. InputStream lIStr = arsResultSet.getBinaryStream(ColumnName);
    3. String lStr = (String)arsResultSet.getObject(ColumnName);
    and then:
    lStr.getBytes("UTF-8"); or lStr.toCharArray();
    I always get questions marks and negative byte values or the
    values: 261,262,263,264,265,266.
    I am using the latest 9.0.1. JDBC Thin drivers and the Oracle
    extensions: OracleResultSet, OracleStatement etc...
    Please let me know what class/method I need, to get the Oracle
    NVARCHAR2 unicode string from the result set into a Java string
    and what method to use to look at the underlying hex codes.
    TIA for any pointers.

    If I use in bdInt=sc.nextInt();a substring cannot be used.
    Does anyone know how I solve this question without substring? Perhapse something I've mentioned above
    sincerely h

  • Help:How to get a java String value from a C char array?

    Hi,everyone,could you help me?
    the following is a C struct that i want to recieve a short message:
    struct MO_msg{
    unsigned long long msgID;          //Message ID
    char      dest_id[21]; //Destination Mobile Phone Number
    char      service_id[10];     //
    Now I want to put the "dest_id " value of this struct into a Java String variable.But I dont know how to implement it!
    The following is a block of source code that i implement this functions.But it cant get a String value ,and throw out a Exception:
    java.lang.NullPointerException
    at java.lang.StringBuffer.append(StringBuffer.java:389)
    JNIEXPORT jint JNICALL Java_md_EMAP_thread_RubeMOTSSX_getMO
    (JNIEnv * env, jobject obj, jint connId, jobject mo){
         struct MO_msg MO;
         tssx_cmpp_api_debug_flag = 1;
         int result = CMPP_Get_MO((int)connId,&MO);
         if (result == 0){
              jclass cls = (*env)->GetObjectClass(env,mo);
              jfieldID msgId = (*env)->GetFieldID(env,cls,"msgId","J");
              jfieldID dest_Id = (*env)->GetFieldID(env,cls,"dest_Id","Ljava/lang/String;");
              jfieldID serviceId = (*env)->GetFieldID(env,cls,"serviceId","Ljava/lang/String;");          
              (*env)->SetLongField(env,mo,msgId,MO.msgID);               
              (*env)->SetCharField(env,mo,dest_Id,*destId);
              (*env)->SetCharField(env,mo,serviceId,MO.service_id);
         return result;
    Please help me!Thanks!

    bschauwe:Thank you for your help!
    Yes,just as you say,using NewString Or NewStringUTF can import a C char array into a Java String variable! But now I have another question,when i use these two functions ,i found that it cant deal with Chinese character!
    do you have such experiences to deal with another language charset?if you have ,can you tell me how to deal with it.

  • How to convert Java string into XML one?

    With SAX I can parse an xml file, but I should create xml file by hands.
    Ok, it's simple, but how to encode java string into XML constant
    like "Hello & goodby" into "Hello & goodby" ?
    Is there a standard method for such special xml characters?

    If you are creating your XML "by hand" then just make sure your hands know that you have to do that. It isn't difficult to write a Java method to do it, if "by hand" means "in Java code". Otherwise your XML is not well-formed. And as far as I know there is no package that takes ill-formed XML and fixes it up.

  • How to implement route cipher using java?

    Hi guys,,,
    I really got a headache solving how to implement route cipher using java lang,,i already got the concept but i really dont get how to implement it using java actually i want to make a presentation of how route cipher works using "adobe flash" but first i will implement it using java coz flash actionscripts are closer to java lang.
    Hope you could post some examples or ideas...i would really appreciate it!
    thank you so much...

    just add an action listener (either keypressed or keytyped) to the frame that you want to record. I did this in NetBeans in about 2 seconds. I can simplify it if you need. As for loging it just write the characters to a file output stream.
    public class test extends javax.swing.JFrame {
        /** Creates new form test */
        public test() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            addKeyListener(new java.awt.event.KeyAdapter() {
                public void keyTyped(java.awt.event.KeyEvent evt) {
                    formKeyTyped(evt);
            pack();
        // </editor-fold>
        private void formKeyTyped(java.awt.event.KeyEvent evt) {
            System.out.println(evt.getKeyChar());
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new test().setVisible(true);
        // Variables declaration - do not modify
        // End of variables declaration
    }

  • How to set proxy authentication using java properties at run time

    Hi All,
    How to set proxy authentication using java properties on the command line, or in Netbeans (Project => Properties
    => Run => Arguments). Below is a simple URL data extract program which works in absence of firewall:
    import java.io.*;
    import java.net.*;
    public class DnldURLWithoutUsingProxy {
       public static void main (String[] args) {
          URL u;
          InputStream is = null;
          DataInputStream dis;
          String s;
          try {
              u = new URL("http://www.yahoo.com.au/index.html");
             is = u.openStream();         // throws an IOException
             dis = new DataInputStream(new BufferedInputStream(is));
             BufferedReader br = new BufferedReader(new InputStreamReader(dis));
          String strLine;
          //Read File Line By Line
          while ((strLine = br.readLine()) != null)      {
          // Print the content on the console
              System.out.println (strLine);
          //Close the input stream
          dis.close();
          } catch (MalformedURLException mue) {
             System.out.println("Ouch - a MalformedURLException happened.");
             mue.printStackTrace();
             System.exit(1);
          } catch (IOException ioe) {
             System.out.println("Oops- an IOException happened.");
             ioe.printStackTrace();
             System.exit(1);
          } finally {
             try {
                is.close();
             } catch (IOException ioe) {
    }However, it generated the following message when run behind the firewall:
    cd C:\Documents and Settings\abc\DnldURL\build\classes
    java -cp . DnldURLWithoutUsingProxy
    Oops- an IOException happened.
    java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
    at java.net.Socket.connect(Socket.java:452)
    at java.net.Socket.connect(Socket.java:402)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:139)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:402)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:618)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:306)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:267)
    at sun.net.www.http.HttpClient.New(HttpClient.java:339)
    at sun.net.www.http.HttpClient.New(HttpClient.java:320)
    at sun.net.www.http.HttpClient.New(HttpClient.java:315)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:510)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:487)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:615) at java.net.URL.openStream(URL.java:913) at DnldURLWithoutUsingProxy.main(DnldURLWithoutUsingProxy.java:17)
    I have also tried the command without much luck either:
    java -cp . -Dhttp.proxyHost=wwwproxy -Dhttp.proxyPort=80 DnldURLWithoutUsingProxy
    Oops- an IOException happened.
    java.io.IOException: Server returned HTTP response code: 407 for URL: http://www.yahoo.com.au/index.html
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245) at java.net.URL.openStream(URL.java:1009) at DnldURLWithoutUsingProxy.main(DnldURLWithoutUsingProxy.java:17)
    All outgoing traffic needs to use the proxy wwwproxy (alias to http://proxypac/proxy.pac) on port 80, where it will prompt for valid authentication before allowing to get through.
    There is no problem pinging www.yahoo.com from this system.
    I am running jdk1.6.0_03, Netbeans 6.0 on Windows XP platform.
    I have tried Greg Sporar's Blog on setting the JVM option in Sun Java System Application Server (GlassFish) and
    Java Control Panel - Use browser settings without success.
    Thanks,
    George

    Hi All,
    How to set proxy authentication using java properties on the command line, or in Netbeans (Project => Properties
    => Run => Arguments). Below is a simple URL data extract program which works in absence of firewall:
    import java.io.*;
    import java.net.*;
    public class DnldURLWithoutUsingProxy {
       public static void main (String[] args) {
          URL u;
          InputStream is = null;
          DataInputStream dis;
          String s;
          try {
              u = new URL("http://www.yahoo.com.au/index.html");
             is = u.openStream();         // throws an IOException
             dis = new DataInputStream(new BufferedInputStream(is));
             BufferedReader br = new BufferedReader(new InputStreamReader(dis));
          String strLine;
          //Read File Line By Line
          while ((strLine = br.readLine()) != null)      {
          // Print the content on the console
              System.out.println (strLine);
          //Close the input stream
          dis.close();
          } catch (MalformedURLException mue) {
             System.out.println("Ouch - a MalformedURLException happened.");
             mue.printStackTrace();
             System.exit(1);
          } catch (IOException ioe) {
             System.out.println("Oops- an IOException happened.");
             ioe.printStackTrace();
             System.exit(1);
          } finally {
             try {
                is.close();
             } catch (IOException ioe) {
    }However, it generated the following message when run behind the firewall:
    cd C:\Documents and Settings\abc\DnldURL\build\classes
    java -cp . DnldURLWithoutUsingProxy
    Oops- an IOException happened.
    java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
    at java.net.Socket.connect(Socket.java:452)
    at java.net.Socket.connect(Socket.java:402)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:139)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:402)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:618)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:306)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:267)
    at sun.net.www.http.HttpClient.New(HttpClient.java:339)
    at sun.net.www.http.HttpClient.New(HttpClient.java:320)
    at sun.net.www.http.HttpClient.New(HttpClient.java:315)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:510)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:487)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:615) at java.net.URL.openStream(URL.java:913) at DnldURLWithoutUsingProxy.main(DnldURLWithoutUsingProxy.java:17)
    I have also tried the command without much luck either:
    java -cp . -Dhttp.proxyHost=wwwproxy -Dhttp.proxyPort=80 DnldURLWithoutUsingProxy
    Oops- an IOException happened.
    java.io.IOException: Server returned HTTP response code: 407 for URL: http://www.yahoo.com.au/index.html
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245) at java.net.URL.openStream(URL.java:1009) at DnldURLWithoutUsingProxy.main(DnldURLWithoutUsingProxy.java:17)
    All outgoing traffic needs to use the proxy wwwproxy (alias to http://proxypac/proxy.pac) on port 80, where it will prompt for valid authentication before allowing to get through.
    There is no problem pinging www.yahoo.com from this system.
    I am running jdk1.6.0_03, Netbeans 6.0 on Windows XP platform.
    I have tried Greg Sporar's Blog on setting the JVM option in Sun Java System Application Server (GlassFish) and
    Java Control Panel - Use browser settings without success.
    Thanks,
    George

  • How To Read RTF file in JAVA?  Using  iText?

    How To Read RTF file in JAVA?  Using  iText?.....
    import java.io.*;
    import com.lowagie.text.*;
    import com.lowagie.text.rtf.*;
    public class RTF3 {
    public static void main(String[] args) {
    // System.out.println("This example generate a RTF file name Sample.rtf");
    // Create Document object
    Document myDoc = new Document();
    try {
    // Create writer to listen document object
    // and directs RTF Stream to the file Sample.rtf
    RtfWriter2.getInstance(myDoc, new FileOutputStream("Sample.rtf"));
    // open the document object
    myDoc.open();
    // Create a paragraph
         Paragraph p = new Paragraph();
         p.add("Helloworld in Rtf file..amazing isn't");
         // Add the paragraph to document object
    myDoc.add(p);
    catch(Exception e) {
    System.out.println(e);
    //close the document
    myDoc.close();
    Exception in thread "main" java.lang.NoSuchMethodError: com.lowagie.text.Rectangle.width()F
         at com.lowagie.text.rtf.document.RtfPageSetting.rectEquals(RtfPageSetting.java:433)
         at com.lowagie.text.rtf.document.RtfPageSetting.guessFormat(RtfPageSetting.java:362)
         at com.lowagie.text.rtf.document.RtfPageSetting.setPageSize(RtfPageSetting.java:341)
         at com.lowagie.text.rtf.RtfWriter2.setPageSize(RtfWriter2.java:248)
         at com.lowagie.text.Document.open(Unknown Source)
         at view.RTF3.main(RTF3.java:23)
    CAN you HELP me?

    import com.lowagie.text.Document;
    import com.lowagie.text.rtf.parser.RtfParser;
    import java.io.FileInputStream;
    String inputFile = "sample.rtf";
    Document document = new Document();
    document.open();
    RtfParser parser = new RtfParser(null);
    parser.convertRtfDocument(new FileInputStream(inputFile), document);

  • Urgent help needed in Java Strings

    Hi guys/gals..
    I want to know how to i Capitalize onlt the first Alphabet of a String.
    Eg if i hav the string "swing". i need it as "Swing" ie the first alpha shud be capitalized. How to do tat. The Java method of toUpperCase wud be of now use since it capitalizes the whole string.
    Tks.
    Divya...

    I use this. Maybe not the most optimal way, but it works :)
         public static String capString(String inp)
          byte[] buf = inp.getBytes();
          // first character is between 'a' and 'z', substract 32 from it to capitalize the character
          if(buf[0] >= 97 && buf[0] <= 122)
           buf[0] -= 32;
          return new String(buf);
         }

  • How to send mail attachments using java mail

    can any one help how to create mails attachments using java mail

    you can do it like this:
    Message msg = new MimeMessage(session);
    String fileAttachment = "c:/test.txt";
    Multipart mp = new MimeMultipart();
    BodyPart bp = new MimeBodyPart();
    FileDataSource fds = new FileDataSource(fileAttachment);
    bp.setDataHandler(new DataHandler(fds));
    bp.setFileName(fds.getName());
    mp.addBodyPart(bp);
    msg.setContent(mp);
    ...

  • How to compare two files in java & uncommon text should print in text file.

    Hi,
    Can any one help me to write Core java program for this.
    How to compare two files in java & uncommon text should print in other text file.
    thanks
    Sam

    Hi All,
    i m comparing two HTML file.. thats why i am getting problem..
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class textmatch{
    public static void main(String[] argv)
    throws Exception{
    BufferedReader fh =new BufferedReader(new FileReader("internal.html"),1024);
    BufferedReader sh = new BufferedReader(new FileReader("external.html"),1024);
    String s;
    String y;
    while ((s=fh.readLine())!=null)
    if ( s.equals(y=sh.readLine()) ){    
    System.out.println(s + " " + y); //REMOVE THIS PRINTLN STATEMENT IF YOU JUST WANT TO SHOW THE SIMILARITIES
    sh.close();
    fh.close(); }
    thanks
    Sam

  • How to compare two files in Java & uncommon text should print in Diff text

    Hi All,
    can any one help me to write a java program..
    How to compare two files in Java & uncommon text should print in Diff text file..
    Thanks
    Sam

    Hi All,
    i m comparing two HTML file.. thats why i am getting problem..
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class textmatch{
    public static void main(String[] argv)
    throws Exception{
    BufferedReader fh =new BufferedReader(new FileReader("internal.html"),1024);
    BufferedReader sh = new BufferedReader(new FileReader("external.html"),1024);
    String s;
    String y;
    while ((s=fh.readLine())!=null)
    if ( s.equals(y=sh.readLine()) ){    
    System.out.println(s + " " + y); //REMOVE THIS PRINTLN STATEMENT IF YOU JUST WANT TO SHOW THE SIMILARITIES
    sh.close();
    fh.close(); }
    thanks
    Sam

  • How to put jsp content in to string butter?

    Hello Friends,
    I'm new to J2EE. please tell me how can I put jsp content into string buffer. following is a part of code I wrote. I'm also reading data from database on some part of code.
    <html>
         <head>
              <title>JSP for AdminForm form</title>
         </head>
         <body style="font-family:verdana;font-size:10pt;"><=<br>
         <%@ include file="header.html" %>
              <html:form action="/admin">
                   <table border="1" width="700" height="500">
                   <tr>
                   <td border="1" width="100" height="5"> Check <br></td>
                   <td border="1" width="100" height="5"> SNo. <br></td>
    </tr>
    <tr>
                   <td border="1" width="150" height="5"> userId <br></td>
                   <td border="1" width="150" height="5"> Role <br></td>
                   <td border="1" width="150" height="5"> Dept. <br></td>
                   <td border="1" width="150" height="5"> Edit <br></td>
                   </tr>
    </table>
    </body>
    </html>
    please help me out.
    Thanks.

    You have to generate a replacement for the default ServletOuputStream so that every time the data is sent to the browser (via the output stream) it is also sent to a tool that can generate a String or StringBuffer (a StringWriter does this nicely). One way to do this is to generate a ServletOutputStream implementation that wraps a ServletOutputStream and StringWriter. You would implement each method in ServletOutputStream and pass the parameters to both wrapped streams, i.e.:
    public class ServletOutputStreamAndStringWriter extends ServletOutputStream {
      private ServletOutputStream sos;
      private StringWriter sw;
      pubic ServletOutputStreamAndStringWriter (ServletOutputStream sos, StringWriter sw) {
        this.sos = sos;
        this.sw = sw;
      public void print(String s) {
        sos.print(s);
        sw.write(s);
      public void println(String s) {
        sos.println(s);
        sw.swrite(s+System.getProperty("line.separator"));
      //etc... for all methods including flushes and closes...
    }Next you have to insert the ServletOutputStream implementation above into the application in a manner that doesn't require a re-write of the rest of your code. The best way to do this is to generate a ServletResponseWrapper implementation that returns your new implementation of the ServletOutputStream in the getOutputStream() method:
    public class SplitOutputServletResponse extends ServletResponseWrapper {
      private ServletOutputStreamAndStringWriter sosasw;
      public SplitOutputServletResponse(ServletResponse sr, ServletOutputStreamAndStringWriter sosasw) {
        super(sr);
        this.sosasw = sosasw;
      public ServletOutputStream getOutputStream() { return sosasw; }
    }Now all you have to do is replace the response you use in your application with this wrapper. The best way to do it is through a Filter:
    public class SplitOutputFilter implements javax.servlet.Filter {
      private FilterConfig fc;
      public void init(FilterConfig fc) { this.fc = fc; }
      public void destroy() { }
      /* This is where the filtering work gets done.  You get a request and a response, you pass the request,
          replace the response, and let the rest of the filter chain do its work (the JSP page gets generated and the
          response to the client is generated).  Then after the rest of the filter chain you get the text out of the
          StringWriter you generated for the ServletOutputStream
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        // After the JSP does its work, the StringBuffer will be generated from this StringWriter
        StringWriter stringBufferFromHere = new StringWriter();
        // This is the tool used to deliver the JSP output to the above StringWriter
        ServletOutputStreamAndStringWriter output = new ServletOutputStreamAndStringWriter (response.getOutputStream(), stringBufferFromHere);
        // And this is the tool used to deliver the above output stream to the JSP pages
        SplitOutputServletResponse sosr = new SplitOutputServletResponse(response, output);
        // Now we replace the incoming ServletResponse with the wrapper generate above for the rest of the FilterChain
        // which includes the actual execution of the JSP
        chain.doFilter(request, sosr);
        // By the time we get to this point, the JSP has already generated the page.  We need to extract the text as
        // a StringBuffer, which we should have access to via the StringWriter
        StringBuffer jspOutput = stringBufferFromHere.getBuffer();
        // Then do whatever you need to do with the buffer...  Note that the FilterContext provides a reference to the
        // ServletContext which could help you store the buffer, put it in DB, or whatever you wanted to do with it...
    }Filters start at the beginning of a request cycle, can be mapped to particular URLs or groups of URLs. To see how to use them see: http://java.sun.com/products/servlet/Filters.html which also has some similar examples.

  • How to convert oracle timestamp to java timestamp

    Hi,
    I need to convert oracle timestamp that i got from oracle database to java timestamp.I tried to use getTimestamp() to get timestamp value from oracle, but am getting NumberFormatException.
    Could any of suggest how to convert oracle timestamp to java timestamp.

    Thanks jverd ,
    then my code will be like:
    String oracleTS="11-MAR-05 11.19.20.625 AM";
    // am looking for yyyy-MM-dd HH:mm:ss format
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd
    HH:mm:ss");           
    Timestamp javaTimestamp=Timestamp.valueOf(oracleTS);
    System.out.println("javaTimestamp----->>
    "+javaTimestamp);
    ving java.lang.NumberFormatException: For input
    string: "MAR"Well, the SimpleDateFormat has to actually match the format you're trying to parse, for one thing. Then you have to actually USE the SDF, which you didn't.
    You really haven't made it clear what you're trying to do, and it doesn't appear that you bothered to study the links I provided.
    DateFormat df = new SimpleDateFormat("dd-MMM-yy HH.mm.ss.SSS aa");
    Date date = df.parse(oracleTS);
    Timestamp ts = new Timestamp(date.getTime());

  • Efficiency of Java String operations

    Hi,
    for an Information Retrieval project, I need to make extensive use of String operations on a vast number of documents, and in particular involving lots of substring() operations.
    I'd like to get a feeling how efficient the substring() method of java.lang.String is implemented just to understand whether trying to optimize it would be a reasonable option (I was thinking of an algorithm for efficient string pattern matching such as the Knuth-Morris-Pratt algorithm, but if java.lang.String already applies similarly efficient algorithms I would not bother).
    Can someone help?
    J

    Thanks for your comment. Yes of course you're right, I
    mean indexOf(). If so (thanks DrClap), let me enter the discussion.
    The indexOf() implements a so called "brute force algorithm".
    The performance is O(n*m), where n is the length of the text, and
    m is the length of the pattern, but is close to n on the average.
    The KMP is O(n), so the performance gain should be hardly noticeable.
    To get a real performance gain you should look at the BM (Boyer-Moore,
    O(n/m)) algorithm or some of its descendants.
    As for java.util.regex package, as far as i understand it should be
    several times slower than indexOf(), because it reads EACH character through an interface method (as opposed to direct array access in indexOf()).
    Though it's still to be proved experimentally.

Maybe you are looking for