Trimming strings

hi
i have retrieved a string fro ma random acess file.when i print it it prints all thse square boxes with it aswell. i tried to use the String.trim() function but it wouldnt allow me to do that,
is there another way to trim the boxes off the end so all i have lkeft is text?r those boxes whitespaces?or r
they null?
here is the code ive got
//get the chars
for (int i = 0; i < temp.length; i++)
temp = realfile.readChar ();
//crate a new string from the char array
String realword = new String (temp);
thanks

hi
i dont know wat the string is because the user inputs
it into a jlist and then the jlist is saved as a
random access file. and then when i try to recall the
file to place it back into the jlist it prints squaresYou do know what the string is (you posted code in another thread, where it was possible to see that you used some kind of record size? You should never write a string that is shorter than record size. Pad it (with spaces) so it always takes up a full record, or store the length of the string some where in the file.
/Kaj

Similar Messages

  • The "write key" configurat​ion file vi use of "trim string" prior to writing the data can modify any string data written.

    I tried to use the config VIs to record some front-panel settings for later restoration, one of which could be a single space character (part of a string parsing system).
    I soon discovered that whenever I tried to save that single-space value to an INI file, only a null string was saved.
    After doing some digging I discovered that buried in the Write Key vi is a worker vi called Config Data Modify that uses Trim String on the string data before it is written to the file and that's what was eating my string character. I don't know whether this is a bug or a feature but there are at least three ways to fix it.
    1) Assuming you want to leave the library VIs alone, you can pre-process any stings sent to "write key" to replace all spaces with "\20" and then post-process all strings read using "read key" to replace all instances of \20 with spaces.
      and if you don't mind modifying the library VIs, either to save/use under a different name or to stick back into the library in a modified state (caution - can cause problems when you move code to another machine with an un-modified library) then...
    2) You can yank the trim-string out of the Config Data Modify vi and hope that it does not have any undesirable side effects with regards to the other routines that use Config Data Modify (so far I have not found any in my limited testing)
    or
    3)  You can modify the string pre-processing vi, Remove Unprintable Chars, to add the space character to the list of characters that get swapped out automatically.
    Note that both option #1 (as suggested above) and option #3 will produce an INI file data entry that looks like    key="\20Hello\20World\20"   while option #2 produces an entry that looks like   key=" Hello World "
    The attached PDF contains screenshots of all this.
    Attachments:
    Binder1.pdf ‏2507 KB

    Hi Warren,
    there's a 4th option:
    Simply set the "write raw string" input of the write key function to TRUE
    This option only appears when a string is wired to that function!
    Just re-checked:
    I think it's a limitation of the config file format. It's text based and (leading) spaces in the value are "overseen" as whitespaces. So your next option would be to use quotes around your string with spaces...
    Message Edited by GerdW on 05-02-2009 08:32 PM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Is trim(both from string) is the same as trim(string)...

    trim(both from string) is the same as trim(string)...
    like in
    SELECT trim(both from STRING_COLUMN) "A" , trim(STRING_COLUMN) "B" from TEXT_TABLE
    will "A" and "B" will be same
    I know this was asked in previous threads , but wanted clarify ..Thanks in advance

    Yes, they are the same
    (See the syntax diagram here http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96540/functions153a.htm#SQLRF06149)

  • When and how to trim string

    Not sure the best way around this issue.  In a query I have the following:
    SUBSTRING(blogStories.blogBody,1,220) AS blogBody
    Later, when I go to display this, I want to strip the html so I have this:
    <cfset trimmedBodyText = REReplaceNoCase(#rsBlog.blogBody#,"<[^>]*>","","ALL")>
    <p><cfoutput>#trimmedBodyText#</cfoutput><em> ... (more)</em></p>
    This is where the problem comes in.  If my SQL query happens to end in the middle of a string like this:
    <p>Web 2.0 tools allow opportunities for doing traditional things in new and fundamentally different ways. As Clay Shirky writes in <a target="_blank" href="http://perma://BLPageReference/75484FCE-115D-450B-A2DF-4F71745B
    Then the REReplaceNoCase causes problems because there is no end tag.
    Can I do this in SQL, or should I pull the whole story, do the REReplaceNoCase and then trim it?  If so, what is the command in ColdFusion for trimming?  Everything I've found only trims spaces. I can't seem to specify a length anywhere.

    OK, I hadn't received an answer and I kept digging and found the LEFT command, so what I have done is changed my query to get the entire story then I run this code for the output
    <cfset variables.blogStory = REReplaceNoCase(#rsBlog.blogStory#,"<[^>]*>","","ALL")>
    <cfset variables.blogStory = Left(#variables.blogStory#, 220)>
    <p>#variables.blogStory#<em>... (more)</em></p></td>
    Then the problem was that sometimes I'd get cut off in the middle of a word, so I've changed it to this to find the last word and remove it:
    <cfset variables.blogStory = REReplaceNoCase(#rsBlog.blogStory#,"<[^>]*>","","ALL")>
    <cfset variables.blogStory = Left(#variables.blogStory#, 220)>
    <cfset variables.lastWord = ListLast(#variables.blogStory#, " ")>
    <cfset variables.trimLength = Len(#variables.lastWord#)>
    <cfset variables.blogStory = Left(#variables.blogStory#, 220-#variables.trimLength#)>
    <p>#variables.blogStory#<em>... (more)</em></p></td>
    This solves the problem for me.  I get the output I want, but I'm sure there is a more elegant way of doing this with less code.  If anyone knows of one, I'd love to hear it.

  • Trim string

    Hi,
    I have this string "nicola milella", I'd like to obtain : "nicolamilella".
    How can I do? I have tried with
    String s = "nicola milella";
    System.out.println(s.trim());
    but it doesn't work.
    thanks

    the trim method only removes spaces from the begining
    and the end of the string.
    You have to:
    1. use a for loop
    2. iterate through the string unil you reach the space
    3. get the index of the spaceif you want to do this, you can use the indexOf method to find the index of the space. You could then use a while loop to keep moving through your string looking for all spaces, using the indexOf method that takes a from index parameter, and stopping when it returns -1 to indicate no more spaces. Unless, of course, you only wanted to eliminate the first space, in which case no while loop is needed.

  • UDF to trim the left or right of a string

    hi,
    My task is that i ave to Trim the left or right most occurances of a Character.For exp
    my input = 003045609800
    than if the characters to be trimmed is '0' than on left & right trim the output should appear as below
    lefttrim=3045609800
    righttrim=003045609800
    Please help me with the Code.
    Thanks in Advance,
    Bhargav

    Hi
    This should be the code that you are looking for
    Left trim.
    @param pstrValue The string to left trim
    @return Returns a left trimmed string
        public static String ltrim(String pstrValue) {
            if (StringUtil.len(pstrValue) > 0) {
                if (pstrValue.charAt(0) == ' ') {
                    if (StringUtil.len(pstrValue.trim()) == 0) {
                        return ""; // This is an empty string
                    } else {
                        // Remove the fist char if it is a space
                         while (pstrValue.charAt(0) == ' ') {
                             pstrValue = pstrValue.substring(1);
                         return pstrValue;
                } else {
                    return pstrValue;
            } else {
                return pstrValue;
    Right trim.
    @param pstrValue The value to right trim
    @return Returns a right trimmed string
        public static String rtrim(String pstrValue) {
            if (StringUtil.len(pstrValue) > 0) {
                if (pstrValue.charAt(pstrValue.length()) == ' ') {
                    if (StringUtil.len(pstrValue.trim()) == 0) {
                        return ""; // This is an empty string
                    } else {
                        // Remove the fist char if it is a space
                         while (pstrValue.charAt(pstrValue.length()) == ' ') {
                             pstrValue = pstrValue.substring(pstrValue.length() - 1);
                         return pstrValue;
                } else {
                    return pstrValue;
            } else {
                return pstrValue;
    regards
    krishna

  • Trim between two strings inside a column

    Hello,
    I have a large data in clob column and string between two values needs to be trimmed to 10 bytes.
    ie. - I need to trim string between <Val> and </Val> to 10.
    CLOB_COL
    <Val>123 Main Street</Val><Addr></Addr><Val>321 Main Street</Val><OtherNode></OtherNode>
    And, I would like my result to be:
    <Val>123 Main S</Val><Addr></Addr><Val>321 Main S</Val><OtherNode></OtherNode>
    What will be the fastest way to update this clob column or probably insert into a new table. (I do not have XML DB installted on this database, so I cannot use XML parser)
    Thanks

    Hi,
    Sorry, I made a mistake.
    Try this:
    SELECT  REGEXP_REPLACE ( '<Val>2010-10-31 16:59:24</Val>'
                            , '(<Val>[^<]{1,3000})'    || -- \1 = <Val> and up to 3000 characters (not <)
                                 '[^<]*'               || -- 0 or more characters (not <) to be removed
                     '(\</Val>)'               -- \2 = </Val>
                            , '\1\2'
                            )     AS val_substring
    FROM    dual;A plus-sign in a pattern means the preceding is repeated 1 or more times.
    I meant to use an asterisk to mean 0 or more times on this row:
    ...                          '[^<]*'               || -- 0 or more characters (not <) to be removed
    --                     +  was here originally 
    By the way, you may have noticed that this site normally doesn't display multiple spaces in a row.
    Whenever you post formatted text (including, but not limited to, code) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    This is especially helpful with regular expressions, not only because they're confusing enough with formatting, but because they use brackets which this site may interpret as markup and not print correctly.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • String.trim() doubt

    Hi,
    why code is comaparing differently ?can you explain me please?
    class TestKing {
    public static void main(String[] args) {
    System.out.println("string".toUpperCase().intern() == "STRING");
    System.out.println("gap1");
    if ("String".trim() == "String".trim())
    System.out.println("Equal");
    else
    System.out.println("Not Equal");
    System.out.println("gap2");
    if("String".toUpperCase() == "String".toUpperCase())
    System.out.println("Equal");
    else
    System.out.println("Not Equal"); // not equa is answere ,why
    output
    true
    gap1
    Equal
    gap2
    Not Equal
    thanks
    ravikumar

    Hi,
    why code is comaparing differently ?can you explain
    me please?
    class TestKing {
    public static void main(String[] args) {
    ystem.out.println("string".toUpperCase().intern() ==
    "STRING");
    System.out.println("gap1");
    if ("String".trim() == "String".trim())
    System.out.println("Equal");
    System.out.println("Not Equal");
    System.out.println("gap2");
    if("String".toUpperCase() ==
    "String".toUpperCase())
    System.out.println("Equal");
    se
    System.out.println("Not Equal");
    // not equa is answere ,why
    output
    true
    gap1
    Equal
    gap2
    Not Equal
    thanks
    ravikumarUse the equals() method to compare two objects. The == operator will only tell you if the contents of two variables are equal.
    Eg.
    "string".equals("string");  //returns trueEDIT: TuringPest beat me to it.
    Message was edited by:
    maple_shaft

  • Parsing String to date

    This is my function to convert a string into a desired output format.But my Date in the desired output format is coming out to be null.Could smeone plz point out my mistake.
    Date getDateInDesiredFormat(String strInputDate,String strInputFormat,String strOutputFormat)
         try
           SimpleDateFormat sdfInput  = new SimpleDateFormat(strInputFormat);
           SimpleDateFormat sdfOutput = new SimpleDateFormat("MM-dd-yyyy");
           ParsePosition pos = new ParsePosition(0);
           Date dtInputDate=sdfInput.parse(strInputDate.trim(),pos);
           System.out.println(dtInputDate);
           String strFormattedDate=sdfOutput.format(dtInputDate);
           System.out.println(strFormattedDate);
           Date dtOutputDate=sdfOutput.parse(strFormattedDate.trim(),pos);
           if(dtOutputDate==null)
                System.out.println("dtOutputDate is null ");
           else
               System.out.println(dtOutputDate.toString());
           return dtOutputDate;
         catch (NullPointerException npex)
             return null;
          catch(Exception ex)
              return null;
       }This is how i am calling the function
    Date date=getDateInDesiredFormat("Fri Sep 30 20:30:56 IST 2006","EE MMM d HH:mm:ss ZZZ yyyy","MM-dd-yyyy");
      }

    You need to use the sdfInput object to parse the date and sdfOutput to format and print it (like you did before your 'if'):
    SimpleDateFormat sdfInput  = new SimpleDateFormat(strInputFormat);
    SimpleDateFormat sdfOutput = new SimpleDateFormat("MM-dd-yyyy");
    Date dtInputDate=sdfInput.parse(strInputDate.trim());
    String strFormattedDate=sdfOutput.format(dtInputDate);
    System.out.println(strFormattedDate);the toString() you use in the else block uses a default format, not the one you specify.

  • Hi all .hope all is well ..A quick trim question

    Hi all
    Hope all is well ......
    I have a quick trim question I want to remove part of a string and I am finding it difficult to achieve what I need
    I set the this.setTitle(); with this
    String TitleName = "Epod Order For:    " + dlg.ShortFileName() +"    " + "Read Only";
        dlg.ShortFileName();
        this.setTitle(TitleName);
        setFieldsEditable(false);
    [/code]
    Now I what to use a jbutton to remove the read only part of the string. This is what I have so far
    [code]
      void EditjButton_actionPerformed(ActionEvent e) {
        String trim = this.getTitle();
          int stn;
          if ((stn = trim.lastIndexOf(' ')) != -2)
            trim = trim.substring(stn);
        this.setTitle(trim);
    [/code]
    Please can some one show me or tell me what I need to do. I am at a lose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

    there's several solutions:
    // 1 :
    //you do it twice because there's a space between "read" and "only"
    int stn;
    if ((stn = trim.lastIndexOf(' ')) != -1){
        trim = trim.substring(0,stn);
    if ((stn = trim.lastIndexOf(' ')) != -1){
          trim = trim.substring(0,stn);
    //2 :
    //if the string to remove is always "Read Only":
    if ((stn = trim.toUpperCase().lastIndexOf("READ ONLY")) != -1){
       trim = trim.substring(0,stn);
    //3: use StringTokenizer:
    StringTokenizer st=new StringTokenizer(trim," ");
        String result="";
        int count=st.countTokens();
        for(int i=0;i<count-2;i++){
          result+=st.nextToken()+" ";
        trim=result.trim();//remove the last spaceyou may find other solutions too...
    perhaps solution 2 is better, because you can put it in a separate method and remove the string you want to...
    somthing like:
    public String removeEnd(String str, String toRemove){
      int n;
      String result=str;
      if ((n = str.toUpperCase().lastIndexOf(toRemove.toUpperCase())) != -1){
       result= str.substring(0,stn);
      return result;
    }i haven't tried this method , but it may work...

  • Global Connection String

    Is there any way to use a global connection string variable for mysql database.
    Currently there are some servlets in my web project.say ,
    Servlet_1
    Servlet_2
    Servlet_3
    Now i have to add these lines for each and every servlet to connect with mysql.
    String driver =  "org.gjt.mm.mysql.Driver";
    String url= "jdbc:mysql://localhost/my_db?user=root&password=dba";apart from that if there is a way to create a global connection string servlet or class i can reuse it with my application.
    please let me know how to do this.

    Ok this my Class for connection string.
    package org.me.AuthAdmin;
    public class ConString
        public ConString()
             String driver =  "org.gjt.mm.mysql.Driver";
              String url= "jdbc:mysql://localhost/my_db?user=root&password=dba"; 
    }Please help me on this. i really don't know what to do here after.
    package org.me.AuthAdmin;
    import java.io.*;
    import java.net.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.me.AuthAdmin.ConString;
    public class AuthAdmin extends HttpServlet
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
                    String postUserName = request.getParameter("txt_un").trim();
              String postUserPwd = request.getParameter("txt_pwd").trim();
                    String db_user_name=null;
                    String db_user_pwd=null;
            try
                //String driver =  "org.gjt.mm.mysql.Driver";
               // String url= "jdbc:mysql://localhost/my_db?user=root&password=dba";
                Class.forName(driver).newInstance();
                Connection con=DriverManager.getConnection(url);
                Statement stmt=con.createStatement();
                String qStr="SELECT * FROM sysusers WHERE user_name = '"+postUserName+"' AND user_pwd = '"+postUserPwd+"'";
                ResultSet rst=stmt.executeQuery(qStr);
                while(rst.next())
                    db_user_name = rst.getString("user_name");
                    db_user_pwd = rst.getString("user_pwd");     
            catch(Exception e)
                throw new ServletException(e);
           if( (postUserName.equals(db_user_name)) && (postUserPwd.equals(db_user_pwd)))
                response.sendRedirect("panel.jsp");
           }else
                response.sendRedirect("error.jsp");
    }

  • 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."

  • Small prob in ignoring string want to skip 2nd value?

    Hi all,
    here CONSTRAINT Adept_Usr_Login NOT NULL ,
    i have three fixed but 2nd is dynamic how to do this here.
    if( tokens0.equalsIgnoreCase( "CONSTRAINT" ) && tokens2.equalsIgnoreCase( "NOT" ) &&
    tokens3.equalsIgnoreCase( "NULL" ) )
    // dataLines.append( " -- " );
    dataLines.append( "NOT " ).append("NULL ").append(" , ").append(" -- ");
    dataLines.append( dataLine ).append( '\n' );
    Can any one give proper suggestion what to de here.
    thanks
    Vijendra

    i don't know whether i will be properly displayable or not.
    import java.util.Enumeration;
    import java.io.*;
    import java.util.StringTokenizer;
    import java.sql.*;
    public class FileReading{
    public static void main(String args[]){
    String file="C:/Documents and Settings/vijendras/Desktop/sampleApplicationchngd.sql";
    //modified by vijendra for ignoring views and stored procedures on 11 Apr 2006
    try {
    // open the file for reading
    FileReader inputstream = new FileReader (file);
    BufferedReader rdr = new BufferedReader( inputstream );
    // the StringBuilder which stores the processed lines
    StringBuffer dataLines = new StringBuffer();
    // read the file line by line
    String dataLine;
    boolean pending=false;
    while((dataLine = rdr.readLine()) != null ) {
    // split the input data into words upto first 3 words only
    //String[] tokens = dataLine.split( " ", 3 );
    String[] tokens = dataLine.trim().split( " ", 3 );
    StringTokenizer st = new StringTokenizer(dataLine.trim()," ");
                        String tokens0 = "";
                        String tokens1 = "";
    if(st.hasMoreTokens()){
                             tokens0 = st.nextToken();
                        if(st.hasMoreTokens()){
                             tokens1 = st.nextToken();
    if (!pending) {
    // if the line starts with 'create' and a 'view' follows it,
    // then add a "--" to the beginning of the line
    if((tokens0.equalsIgnoreCase( "create" ) && tokens1.equalsIgnoreCase( "view" ) )||
    (tokens0.equalsIgnoreCase( "create" ) && tokens1.equalsIgnoreCase( "procedure" ))
                             //state #2
                             // dataLines.append( "-- " );
                             // dataLines.append( dataLine ).append( '\n' );
                             pending = true;
                   // added by vijendra for modifying CONSTRAINT NAME NOT NULL to NOT NULL on 30 June 2006
                        //System.out.println(tokens[ 0 ].trim()+"::::"+tokens[ 1 ].trim()+"::::"+tokens[ 2 ].trim());
    if( tokens[ 0 ].trim().equalsIgnoreCase( "CONSTRAINT") && tokens[ 2 ].trim().equalsIgnoreCase( "NOT NULL," ) ){
    dataLines.append( " NOT " ).append(" NULL ").append(" , ").append(" -- ");
    dataLines.append( dataLine ).append( '\n' );
              System.out.println( "Executed");
                             else {
                             //state #1
                             // you're not in a[nother] view/proc yet}
                                  //dataLines.append( "-- " );
                                  dataLines.append( dataLine ).append( '\n' );
                   if (pending) { // don't use 'else'
                        //line contains ';'
                   if (!dataLine.endsWith(";")) {
                                  //state #4
                                  // do whatever... you're finished
                             dataLines.append( "-- " );
                             dataLines.append( dataLine ).append( '\n' );
                                  else {
                             //     state #3
                                  //you're in continuation of view/proc
                                  //but haven't found end yet
                                  dataLines.append( "-- " );
                                  dataLines.append( dataLine ).append( '\n' );
                             pending = false;
         /*Note the 'if' I marked "don't use else" which allows the logic to fall through and catch both
         states #2 and #4 (start and end) on the same line.*/
    rdr.close(); // close the file
    inputstream.close();
    // open the file for writing new data to it
    FileWriter outputstream=new FileWriter( file );
    BufferedWriter writer = new BufferedWriter(outputstream);
    // write the new StringBuilder's data back to the file.
    writer.write( dataLines.toString(), 0, dataLines.length() );
    writer.close(); // close the file
    outputstream.close();
    } catch( IOException e ) {
    System.out.println("Exception"+e);
    out put of sql file is now this but it sholud be applied to all.
    CREATE TABLE Adept_User(
    Id NUMBER(10, 0)     NOT NULL,
    Login_Name VARCHAR2(30)
    NOT NULL , -- CONSTRAINT Adept_Usr_Login NOT NULL,
    First_Name VARCHAR2(35)
         CONSTRAINT Adept_Usr_First_name     NOT NULL,
    Last_Name VARCHAR2(35),
    User_Password VARCHAR2(10)
         CONSTRAINT Adept_Usr_Last_name     NOT NULL,
    User_Status NUMBER(10, 0)
         CONSTRAINT Adept_Usr_Status     NOT NULL,
    User_Type NUMBER(10, 0)
         CONSTRAINT Adept_Usr_Type     NOT NULL,
    Customer_Contact NUMBER(10, 0),
    Employee NUMBER(10, 0),
    Organization Number(10,0),
    Password_Modified_Date DATE,
    Currency_Master_Id NUMBER(10, 0),
    CONSTRAINT PK23 PRIMARY KEY (Id)
    CREATE TABLE Adept_User_Group(
    Id NUMBER(10, 0) NOT NULL,
    Adept_Group NUMBER(10, 0)
         CONSTRAINT Adept_Usr_Grp     NOT NULL,
    Adept_User_Name NUMBER(10, 0)
         CONSTRAINT Adept_Usr_name     NOT NULL,
    CONSTRAINT PK157 PRIMARY KEY (Id)
    CREATE TABLE Adept_User_Permission(
    Id NUMBER(10, 0)     NOT NULL,
    Adept_Screens NUMBER(10, 0)
         CONSTRAINT Adept_Usr_Perm_Scren     NOT NULL,
    Adept_User_Group NUMBER(10, 0)
         CONSTRAINT Adept_Usr_Grp     NOT NULL,
    Dashboard char(1),
    CONSTRAINT PK28 PRIMARY KEY (Id)
    sorry for inconvinience for reading this all.
    if there is some better way to show all plese tell me.
    Vjendra

  • Need help to convert this format of string in a int value?

    public static int isNumber( String number, int defaultValue ) {
              int result;
              try {
                   result = Integer.parseInt(number);
              } catch( Exception e ) {
                   result = defaultValue;
              return result;
         }Hi, I have the above method that converts a string Number into a int value. It works fine if the string is a normal number 234 (without spaces) but I have a string in the following format:
    *(space)�23,000(space).*
    That is I have a "space" then a "Pound" sign then two numbers then a comma followed by three numbers and then a space again.
    Is there any way I can convert this format into a simple int value?
    Thanks for any guidance.
    Zub

    Hi, I tried the following code but it don't seem to work
         public static int isNumberTrimSpaces( String number, int defaultValue ) {
              number.trim();
              String parsed = "";
              for (int i = 0 ; i < number.length() && number.charAt(i) != ',' ; i++)
             if (Character.isDigit(number.charAt(i))) {
             parsed += number.charAt(i);}
              int result;
              try {
                   result = Integer.parseInt(number);
              } catch( Exception e ) {
                   result = defaultValue;
              return result;
         }Any Ideas? Also will the loop get rid of the pound sign?

  • Jdbc, string and SQL Server's varbinary

    Hi,
    I have a problem, of course otherwise I wouldn't ask for help :)
    So I entered some test data in SQL Server Tables with some varbinary
    types for primary keys. The fields that where put with newid() are the
    problem. Normaly the data should have been put there with jdbc but also
    with newid(). When I try to match them against the same
    data but that was first get from db through jdbc as a string the
    comaparision fails! If for example I get the value for an pk column and
    I put in variable x_pk when I try the select in java:
    ... sql = "Select * from" + tableName + "where pk = " + castSQL(x_pk)
    where castSQL() is for varbinary data type cast from string:
         * Method to cast the strings with pk for sql server.
         * @param str ( String ) the string wilth the pk
         private String castSQL( String str ){
                        String s = str.trim();
                        String ss = "cast (" + asString(s) + "as varbinary)";
         return ss.trim();
    and asString() put the ' around it,
    this select will not work even if the values are the same!!!
    But probalby are not quite the same, something happens on the road in
    getting it from db to string and then cast it to varbinary to compare
    against the value from db.
    So if someone has already encountered this please help me.
    Regards,
    Adrian

    You can't. They're lost forever in the black abyss of the forums.

Maybe you are looking for