Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java: Filtering spaces out of a string?

Options
  • 21-03-2006 6:29pm
    #1
    Registered Users Posts: 45,907 ✭✭✭✭


    Here is the problem.

    I have a variable 'name' which can hold a string value. For illustration i shall use 'Home Edition'. I need to use that variable value in a URL as an option, ie. inventoryeditdelete?option=Home+Edition where the '+' takes the place of the space. I need to be able to filter the String so that 'Home Edition' becomes 'Home+Edition'

    As things stand, when i try to pass the variable only the first part of the string is passed (Home) and i can not use this to query a SQL database from the next page (which is what i need to do)

    Does anyone know some easy code that will allow me to filter the string so the 'space' is replaced with '+'.


Comments

  • Closed Accounts Posts: 13 hermann


    name=name.replace(' ','+');


    From the Java doc:
    http://java.sun.com/j2se/1.3/docs/api/java/lang/String.html#replace(char,%20char)
    replace

    public String replace(char oldChar,
    char newChar)

    Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

    If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a new String object is created that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar.

    Examples:

    "mesquite in your cellar".replace('e', 'o')
    returns "mosquito in your collar"

    Parameters:
    oldChar - the old character.
    newChar - the new character.
    Returns:
    a string derived from this string by replacing every occurrence of oldChar with newChar


  • Registered Users Posts: 45,907 ✭✭✭✭Mitch Connor


    superb - thanks very much.


  • Registered Users Posts: 21,264 ✭✭✭✭Hobbes


    hermann wrote:
    name=name.replace(' ','+');

    That will work but if he is doing a URL (which it oddly looks like) he needs to escape out other characters as well. For that you should use.

    URLEncoder.encode() (as far as I remember). UrlDecoder.decode() to change it back.

    Although spaces would be converted to %20, so the replace beforehand would be best.


  • Registered Users Posts: 45,907 ✭✭✭✭Mitch Connor


    while i have people's attention - does anyone know why a text field would be cutting of values?

    I'm taking values from a database and trying to display the to a text field (using a text field cause i want the user to be able to edit the information if they need to) The Database value is, for instance, 'for home use', the value of the string i pass it into (checked it by displaying the string inside a label) is 'for home use' but when i try to use it in the text field it comes out as 'for'

    Confused the piddle out of me!


  • Registered Users Posts: 45,907 ✭✭✭✭Mitch Connor


    here is the code i have, if it is of any help:
    <html>
    <!-- import statement to include SQL library -->
    <%@ page import="java.sql.*" %>
    <head>
    <title>
    InventoryEditDelete
    </title>
    <link type="text/css" rel="stylesheet" href="style.css"></link>
    </head>
    <jsp:useBean id="InventoryEditDeleteBeanId" scope="session" class="eis.InventoryEditDeleteBean" />
    <jsp:setProperty name="InventoryEditDeleteBeanId" property="*" />
    <body>
    <h1>
    Inventory Edit/Delete Page
    </h1>
    <%
    
    String InventoryOption = request.getParameter("option");//option is a variable passed from another jsp page.
    String ConvertedOption = InventoryOption.replace('+',' ');
    String userName="********";
    String password="*********";
    String url = "jdbc:oracle:thin:@witnt07.wit.ie:1521:orawit";
    String query = "select item_no,name,description,sale_price,cost_price,tax_rate,category1,sub_category,supplier,expiration_date,warehouse,qty_in_stock,min_stock_level,reorder_level from inventory where name = '"+ ConvertedOption +"'";
    try
    {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    }
    catch (ClassNotFoundException e)
    {
    System.err.print("ClassNotFoundException: " + e);
    }
    
    try
    {
    Connection con = DriverManager.getConnection(url, userName, password);
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(query);
    
    while (rs.next())
    {
    String itemnum = rs.getString("item_no");
    String name = rs.getString("name");
    String description = rs.getString("description");
    String saleprice = rs.getString("sale_price");
    String costprice = rs.getString("cost_price");
    String taxrate = rs.getString("tax_rate");
    String category = rs.getString("category1");
    String subcategory = rs.getString("sub_category");
    String supplier = rs.getString("supplier");
    String expirationdate = rs.getString("expiration_date");
    String warehouse = rs.getString("warehouse");
    String qtyinstock = rs.getString("qty_in_stock");
    String minstocklevel = rs.getString("min_stock_level");
    String reorderlevel = rs.getString("reorder_level");
    %>
    
    <label for="user">Name:</label><input type="text" name="txtName" value=<%=rs.getString("name")%>><br />
    <label for="user">Description:</label><input type="text" name="txtDescription" value=<%=description%> ><br />
    <label for="user">Sale Price:</label><input type="text" name="txtSalePrice" value=<%=saleprice%>><br />
    <label for="user">Cost Price:</label><input type="text" name="txtCostPrice" value=<%=costprice%>><br />
    <label for="user">Tax Rate:</label><input type="text" name="txtTaxRate" value=<%=taxrate%>><br />
    <label for="user">Category:</label><input type="text" name="txtCategory" value=<%=category%>><br />
    <label for="user">Sub Category:</label><input type="text" name="txtSubCategory" value=<%=subcategory%>><br />
    <label for="user">Supplier:</label><input type="text" name="txtSupplier" value=<%=supplier%>><br />
    <label for="user">Expiration Date:</label><input type="text" name="txtExpirationDate" value=<%=expirationdate%>><br />
    <label for="user">Warehouse:</label><input type="text" name="txtWarehouse" value=<%=warehouse%>><br />
    <label for="user">Quantity in Stock:</label><input type="text" name="txtQtyInStock" value=<%=qtyinstock%>><br />
    <label for="user">Minimum Stock Level:</label><input type="text" name="txtMinStockLevel" value=<%=minstocklevel%>><br />
    <label for="user">Reorder Level:</label><input type="text" name="txtReorderLevel" value=<%=reorderlevel%>><br />
    <br />
    <%}
    
    stmt.close();
    con.close();
    }
    catch(SQLException e)
    {
    System.err.println("SQLException: " + e);
    }%>
    
    </body>
    </html>
    


  • Advertisement
  • Closed Accounts Posts: 1,651 ✭✭✭Enygma


    Put double quotes around the value attributes in the text elements.


  • Registered Users Posts: 4,003 ✭✭✭rsynnott


    By the way, SQL injection! Look it up.


  • Closed Accounts Posts: 453 ✭✭nuttz


    rsynnott wrote:
    By the way, SQL injection! Look it up.

    If you are refering to the above code, there is a placeholder in use, in the form of the 'query' String, so I dont think you will be very sucessful injecting your SQL there.

    It's never a good idea except in prototypes to put SQL in a JSP.


  • Registered Users Posts: 4,003 ✭✭✭rsynnott


    nuttz wrote:
    If you are refering to the above code, there is a placeholder in use, in the form of the 'query' String, so I dont think you will be very sucessful injecting your SQL there.

    Er, are we looking at the same code?
    String query = "select item_no,name,description,sale_price,cost_price,tax_rate,category1,sub_category,supplier,expiration_date,warehouse,qty_in_stock,min_stock_level,reorder_level from inventory where name = '"+ ConvertedOption +"'";
    


  • Closed Accounts Posts: 453 ✭✭nuttz


    rsynnott wrote:
    Er, are we looking at the same code?
    String query = "select item_no,name,description,sale_price,cost_price,tax_rate,category1,sub_category,supplier,expiration_date,warehouse,qty_in_stock,min_stock_level,reorder_level from inventory where name = '"+ ConvertedOption +"'";
    

    oops! I didn't look athe entire line and missed the all important:
    name = '"+ ConvertedOption +"'";
    

    My mistake. Yep OP, you should probably change that. Do some validation on the string received.
    Also try using PreparedStatement instead.
    PreparedStatement ps;
    .
    .
    .
    String qry = "SELECT * FROM whatever WHERE whoever = ? ";
    ps = con.prepareStatement(qry);
    ps.setString(1, ConvertedOption );
    rs = ps.executeQuery();
    


  • Advertisement
Advertisement