String Trim

Hello,
I'm new to Java programming, I have programmed in other languages. Heres my problem:
At the console someone enters say... "monkee1;monkee2;monkee3 -a -b -c"
how can i trim it to just "monkee1;monkee2;monkee3 -a -b -c" getting rid the white space
Thanks in advance

My solution asumed that 1 space must be kept.You are probably right, so, my version needs to be upgraded to[...]
String tmp;
String del; // new
  else if ( ";".equals(tmp) ) {
    // arg delimiter -> reset
    helper.append(tmp);
    result.add(helper.toString());
    helper.delete(0, helper.length());
    del = ""; // new
  else {
    // arg text
    helper.append(del); // new
    helper.append(tmp);
    del = " "; // new

Similar Messages

  • String Trimming Issue

    Hello, All.
    In one of my JSP's, I retrieve search parameters a user entered on a form add it to the session. I then redisplay the data to the when they return to the JSP. What's happening is that when the data is redisplayed in the text fields, it shows as if there are leading spaces or tabs. I do a string trim before I add the data to the session, but this does not seem to work. I have also tried trimming the string after retrieving the data from the session object.
    I have also confirmed that the length of the data item placed in the session is the same as the length of the item once I retrieve it from the session. I'm not sure, but I believe it may be inserting tabs into the text fields. Anyone out there know what's going on? Any assistance is appreciated. Thanks much.

    I use the following code to retrieve the data from the html form and run it through my cleanParam method, which just trims it:
    String name = cleanParam(request.getParameter("compname"));
    I then add the code to the session after I've performed processing on the data:
    session.setAttribute("name", name);
    The html form has the following code to display data:
    <input type="text" name="compname" size="30" maxlength="30" value=
    <%if(!isEmptyString(getSessionString(session, "name"))){%>"
    <%= session.getAttribute("name") %>"<%}else{%>"<%=name%>"<%}%>>
    Thanks.

  • 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

  • String.trim() bug...

    In this case String.trim() returns "hello "
    The character it has trouble trimming is known in HTML as & n b p s ;
    Is this a bug? it certainly looks like white space if you ask me.
    public class NoBreakTrimTest {
      public static void main(String[] args) {
        char c = 0x00A0;
        String input = "hello" + c;
        String trimmed = input.trim();
        System.out.println("Trimmed: " + trimmed);
        boolean equal = trimmed.equals("hello");
        System.out.println("Equal: " + equal);
    }

    Err that was a joke ;-)Not completely, no. This sort of thread has a tendency to degenerate quite quickly into a flamewar when the OP won't accept that it isn't a bug. Seems easier to just let them file a bug report and get on with other things!
    OP, if it's a bug, please show us what part of the
    specification of String.trim() is being violated.I'd add to that, "be prepared to reverse your belief in this bug, if it is shown not to be a bug".

  • String.trim() problem.

    Hi
    I have an ascii file that I parse, the first like is
    " hello there "
    When I do a trim() on the String. It returns:
    " hello there "
    If I do:
    Character.isSpaceChar(str.charAt(0))
    It returns true.
    If I go into into the file using a text editor and delete the spaces and replace them, the trim() work.
    It seems that the characters are not white spaces, although isSpaceChar returns true.
    Any ideas?
    Thanks
    George

    You might use regex and the space categories "\\p{IsZs}" or "\\p{Zs"}
    [url http://www.fileformat.info/info/unicode/category/Zs/list.htm]http://www.fileformat.info/info/unicode/category/Zs/list.htm
    [url http://unicode.org/Public/UNIDATA/UCD.html#General_Category_Values]http://unicode.org/Public/UNIDATA/UCD.html#General_Category_Values
    [url http://www.fileformat.info/info/unicode/category/index.htm]http://www.fileformat.info/info/unicode/category/index.htm
    Sun's Regular Expression Tutorial for Java
    Regular-Expressions.info
    str = str.replaceAll("^[\\s\\p{Zs}\\p{Zl}\\p{Zp}]*\\b(.*)\\b[\\s\\p{Zs}\\p{Zl}\\p{Zp}]*", "$1");seems like it might work, but it might also be overkill.

  • A question about string.trim()

    I got a fragment of code as follows:
    String s = "abcd ";
    boolean a = (s.trim()=="abcd");
    boolean b = (s =="abcd ");
    Why a is false, b is true?

    The reason why the below code has true assigned to be is quite easy to explain:
    String s = "abcd";
    String y = "abcd";
    boolean b = (s == y);
    ...The String class has a "Pool" of strings. When you use String literals; the compiler automatically checks if it is in the String pool already and if it exists; a reference to that String is returned; if not a new entry in the pool is added and then you get a reference to that. This is only true for Stirng literals and String created using the intern() method.
    If you compile this code you will see that the strings are not equal:
    public static void main(String args[])
      String s = "abcd";
      String y = args[0];
      boolean b = (s == y);
      System.out.println(b);
    }This is because the "abcd" is in the String pool when your program starts; but because the value "abcd" passed in (is not created in the pool automaticlaly). Therefor they are two different String objects.
    This code block shows that you can add Strings to the pool. The intern() method checks to see if the String is in the pool already and if it is it will return you a reference to it; if not it will create one and then return it.
    public static void main(String args[])
      String s = "abcd ";
      String y = args[0].intern();
      boolean b = (s == y);
      System.out.println(b);
    }- Chris

  • String trim() does not work

    Here is the code:
    String item = " abc ";
    int before = item.length();
    item.trim();
    int after = item.length();
    The result is before == after.
    What's wrong?

    Remember that Strings in Java are immutable, so calling item.trim() does nothing to the original String. Did you notice that the trim() method returns a String? The String that is returned is the new String that has been trimmed. So, you must assign this new value to the item variable.
    item = item.trim();
    SAF

  • I get an error when I try to trim my string during run-time??

    I am able to get the string inputted in without the trim.. but when i add the trim, the program screws up during run-time..
    i have this in my code...
    input = in.readLine();
    when i put the following afterwards.. it doesn't work:
    input = input.trim();
    what should i do that I am not doing? or what am I doing wrong?

    You don't specify what the error is, if it's a NullPointerException then you just need to check
    if (input != null) {
        String trimmed = input.trim();
        ...

  • 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

  • Exception in thread "main" java.lang.NumberFormatException:For input String

    this is a code about arrylist. but when I debug it.it metion:Exception in thread "main" java.lang.NumberFormatException:For input String at java.lang.NumberFormatException.forInputString(numberFomatExceptionio java:48)
    at java.lang.Integer.parseInt(integer.java:468)
    at java.lang.Integer.parseInt(integer.java:497)
    at Get.getInt(manerger.java:208)
    at LinkList.insertFirst(manager.java:94)
    at manager.main(manager.java;20)
    this is my code:
    import java.io.*;
    import java.lang.*;
    public class manager
         public static void main(String args[]) throws IOException
         LinkList list=new LinkList();
         System.out.println("input S can scan the grade\ninput D can delete one entry\ninput U can update the entry\ninput A can add one entry\ninput E can end");
         int cr=System.in.read();
    switch(cr)
         case 'A':
         list.insertFirst();break;//this is 20 row
         case 'S':
         System.out.println("input the s");break;
         case 'D':
         System.out.println("input the d");break;
         case 'U':
         System.out.println("input the u");break;
    class Link
    public int number;
    public String name=new String();
    public int chs;
    public int eng;
    public int math;
    public Link next;
    public Link(int number,String name, int chs,int eng,int math)
    this.number=number;
    this.name=name;
    this.chs=chs;
    this.eng=eng;
    this.math=math;
    public Link()
         this(0,"",0,0,0);
    public void displayLink()
    System.out.println(number + " "+name+ " "+chs+ " "+eng+ " "+math+ " ");
    class LinkList
    public Link first;
    public LinkList()
    first = null;
    public boolean isEmpty()
    return first==null;
    public void displayList()
         System.out.println("");
         Link current=first;
         while(current!=null)
              current.displayLink();
              current=current.next;
         System.out.println("");
    public Link insertFirst() throws IOException
         Get getdata=new Get();
         int number=getdata.getInt();//this is 94 row
         String name=getdata.getString();
         int chs=getdata.getInt();
         int eng=getdata.getInt();
         int math=getdata.getInt();
         Link newLink = new Link(number,name,chs,eng,math);
         first=newLink;
         return first;
    public Link find(int key)
         Link current=first;
         while(current.number!=key)
              if(current.next==null)
              return null;
              else
              current=current.next;
         return current;
    public Link update(int key) throws IOException
         Link current=first;
         while(current.number!=key)
         if(current.next==null)
         return null;
         else
              System.out.println("Input the first letter of the subject:");
         int c=System.in.read();
         Get get=new Get();
              switch(c)
                   case 'c':
                   current.chs=get.getInt();break;
                   case 'e':
                   current.eng=get.getInt();break;
                   case 'm':
                   current.math=get.getInt();break;
         return current;
    public float average(char key)
         Link current=first;
         float total=0;
         float average=0;
         float counter=0;
         if(current==null)
         return 0;
         while(current!=null)
              switch(key)
                   case 'c':
                   total=current.chs+current.next.chs;break;
                   case 'e':
                   total=current.eng+current.next.eng;break;
                   case 'm':
                   total=current.math+current.next.math;break;
              current=current.next.next;
              counter++;
         average=total/counter;
         return average;
    public Link delete(int key)
         Link current=first;
         Link previous=first;
         while(current.number!=key)
              if(current.next==null)
              return null;
              else
                   previous=current;
                   current=current.next;
              if(current==first)
              first=first.next;
              else
              previous.next=current.next;
              return current;
    class Get
    public static String getString() throws IOException
    System.out.println("Input your name:");
    InputStreamReader str = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(str);
    String s = br.readLine();
    return s;
    public static int getInt() throws IOException
    System.out.println("Input your data:");
    String st = getString();
    return Integer.parseInt(st);//this is 208 row
    }

    It may be that the code in getString() returns a
    String that ends with a newline. If that is the
    problem, you can use
    return (Integer.parseInt(st)).trim();1. getString will never return a String ending in newline. BufferedReader.readLine strips off the newline.
    2. Even if you had a newline, String.trim doesn't trim newlines.
    3. You would need to trim the String, not the int:
    return (Integer.parseInt(st.trim()));As JimDinosaur said, you are passing bad data (the value of "st").
    In getInt, add this before trying to parse "st":
    System.out.println("###"+st+"###");What does it print?

  • Spliting a string based on Non Printable character

    Hi,
    i have a requirement where i have to split a String based in non printable character " MYU(ascii: 230);
    es: ""This is to test æ raaaaaaaaaaaaaaaaa æ AAA010224544 æ 7118288888 æ
    æ is a not printable character and its ascci is 230..
    iam getting that string from form how to split it in Java..
    Any suggestions...?

    One of many ways
        String initString = "This is to test æ raaaaaaaaaaaaaaaaa æ AAA010224544 æ 7118288888 æ";
        String[] tokens = initString.split(String.valueOf((char)230));
        for (String string : tokens)
          System.out.println(string.trim());
        }

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

  • String subtraction

    String cannot be subtracted......but i want the following.
    example1:
    input:
    str1="abc   332.0";
    str2="332.0"
    output:
    str3=str1-str2="abc"
    example2:
    input:
    str1="  332.0   abc ";
    str2="332.0"
    output:
    str3=str1-str2="abc"how can i do this ?

    You can't, based on the data you show, unless an
    arbitrary decision is made.
    The common parts of str1 and str2 are the numbers, so
    it's possible to remove them by comparing the
    strings. That leaves the letters and spaces of str1.
    You want the spaces removed, which requires an
    arbitrary trimming of the string. See the
    String.trim() method.
    Looh at the String methods indexOf and substring to
    remove the numbers.hmmm...ok, at last i have to follow that way..... i thought if i could do it in less code in a compact way. the code would be bulky i suppose.
    i would like to make a function and that function would take those two input and return the result
    thanks for the quik reply

  • Questions on StringTokenizer, trim(), and parsing.

    im doing an assignment that requires parsing and havent had that much practice with parsing regular text from a file, ive been doing mostly parsing from a html. my question is if im parsing a line and i need 2 different types of information from it, should i just tokenize it twice or do it all at once, assuming the text format is always the same. for example
    String input= "this is a test[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]";if parsed correctly with StringTokenizer it would be 4 Strings(this is a test) and 10 ints for the countdown of numbers. now since the Strings doesnt have a delimiter such as a comma i can use the default delimiter which is the whitespace but then would that mean i would have to parse that same String twice since the numbers has "," has a delimiter? also should i worry about the whitespace that is separating the numbers after the comma? i did a small driver to test out the trim() using this and both outputs were the same. this may be a dumb question but if i call the trim() it eliminates the white space right, therefore i can just set "," as my delimiter, question is why is my output for both Strings the same?
        String input= "this is a test[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]";
        String trimmed = test.trim();
        System.out.println(input);
        System.out.println("\n" + trimmed);SORRY if its confusing im trying not to reveal too much of the hw assignment and just get hints on parsing this efficiently. Thanks in advance

    similar example on how to parse out the numbers with
    "," as a delimiter. thanks in advanceThe following is a simple recursive descent parser to parse a comma delimited list of numbers "(1, 2, 3, 5, 6)". The grammar parser by this code is
    START -> LPAREN LIST RPAREN
    LIST -> NUMBER TAIL
    TAIL -> COMMA LIST | LambdaThe nonterminals NUMBER, LPAREN, RPAREN, and COMMA are defined by the regular expressions in the code.
    Lexical analysis is done by the function advanceToken(). It stores the next token in the variable "lookahead" for further processing. The parse tree is represented recursively through the functions start(), lparen(), rparen(), list(), number(), tail(), comma(), which match the corresponding symbols in the grammar. Finally, translation is done in the function number(). All it does is put the numbers it finds into the List intList. you can modify it to your needs.
    This code originally parsed simple arithmetic expressions, but it took only ten minutes to parse lists of integers. It's not perfect and there are several obvious improvement that will speed up performance, however the strength of the design is that it can be easily changed to suit a variety of simple parsing needs.
    import java.util.regex.*;
    import java.util.*;
    public class RDPParenList {
        private static final Pattern numberPat=
                        Pattern.compile("([1-9]\\d*)|0");
        public static final Object NUMBER = new Object();
        public static final Pattern commaPat = Pattern.compile(",");
        public static final Object COMMA = new Object();
        public static final Pattern lparenPat=
                        Pattern.compile("\\(");
        public static final Object LPAREN = new Object();
        public static final Pattern rparenPat=
                        Pattern.compile("\\)");
        public static final Object RPAREN = new Object();
        public static final Token NULLTOKEN = new Token(null, null);
        String input;
        String workingString=null;
        Token lookahead=NULLTOKEN;
        List intList = new ArrayList();
        /** Creates a new instance of RecursiveDescentParse */
        public RDPParenList(String input) {
            this.input=input;
        public void parse(){
            workingString=input;
            advanceToken();
            start();
            if(! "".equals(workingString))
                error("Characters still remaining in input '" + workingString + "'");
        private void advanceToken() {
            // calling advanceToken must give a token
            if("".equals(workingString))
                error("End of input reached unexpectedly");
            // prune the old token, and whitespace...
            if(lookahead != NULLTOKEN){
                int cutPoint = lookahead.symbol.length();
                while(cutPoint < workingString.length() &&
                        Character.isWhitespace(workingString.charAt(cutPoint))){
                    ++ cutPoint;
                workingString=workingString.substring(cutPoint);
            // Now check for the next token, starting with the null token...
            if("".equals(workingString)){
                lookahead=NULLTOKEN;
                return;
            Matcher m=numberPat.matcher(workingString);
            if(m.lookingAt()){
                lookahead=new Token(m.group(), NUMBER);
                return;
            m=commaPat.matcher(workingString);
            if(m.lookingAt()){
                lookahead=new Token(m.group(), COMMA);
                return;
            m=lparenPat.matcher(workingString);
            if(m.lookingAt()){
                lookahead=new Token(m.group(), LPAREN);
                return;
            m=rparenPat.matcher(workingString);
            if(m.lookingAt()){
                lookahead=new Token(m.group(), RPAREN);
                return;
            error("Error during lexical analysis. Working string: '" +
                           workingString + "'");
        private void start() {
            lParen(); list(); rParen();
        private void lParen(){
            if(lookahead.attrib == LPAREN){
                advanceToken();
                // OK. Do nothing...
            else error("Error at token '" + lookahead.symbol + "' expected '('");
        private void rParen(){
            if(lookahead.attrib == RPAREN){
                advanceToken();
                // OK. Do nothing...
            else error("Error at token '" + lookahead.symbol + "' expected ')'");
        private void list() {
            number(); tail();
        private void number() {
            if(lookahead.attrib == NUMBER){
                // Do something with the number!
                try{
                    intList.add(new Integer(lookahead.symbol));
                catch(NumberFormatException e){
                    // This shouldn't happen if the lexer is working...
                    e.printStackTrace();
                    error("Unknown Error");
                advanceToken();
            else error("Error at token '" + lookahead.symbol + "' expected a number");
        private void tail() {
            if(lookahead.attrib == COMMA){
                comma(); list();
            else {
                // Lambda production
        private void comma() {
            if(lookahead.attrib == COMMA){
                advanceToken();
                // OK. Do nothing...
            else error("Error at token '" + lookahead.symbol + "' expected ','");
        private void error(String message){
            System.out.println(message);
            System.exit(-1);
        public static class Token{
            public Token(String symbol, Object attrib) {
                this.symbol=symbol;
                this.attrib=attrib;
            public String symbol;
            public Object attrib;
        public static void main(String []args){
            if(args.length == 0)
                return;
            System.out.println("\nParse String: " + args[0]);
            RDPParenList p=new RDPParenList(args[0]);
            p.parse();
            System.out.println("OK!");

  • How do I change this string  Please someone help this newbie :)

    Hi All
    I have a string which is a list of file in a folder. I am putting this list into a submenu. The files are formated like this
    Jesse_Smith_08_08_2001
    Jackie_Test_04_04_2000
    I would like to view them like this
    Jesse Smith 08.08.01
    Jackie Test 04.04.00
    How can I do this
    PLEASE HLEP ME
    I have spent 2 days trying to do this
    Craig

    Thanks for the code tolmark
    Can I ask one more this?
    How can I integrate your code into this code ??
    private void addItem(JMenu menu, char a)
        //Get file names from folder "Epod Configuration/Orders To Upload/"
        File dir = new File("Epod Configuration/Orders To Upload");
        File[] files = dir.listFiles();
        for (int j=0; j < files.length; j++)
          String trim = ""+files[j];
          int ndx;
          if ((ndx = trim.lastIndexOf('/')) != -1) trim = trim.substring(ndx+1);
          if (trim.charAt(0) == a);
          String s = trim;
          int idx = s.lastIndexOf('.');
          // remove extension
          if (idx != -1)
            s = s.substring(0, idx);
          System.out.println(s);
            JMenuItem mi = new JMenuItem(s);
            menu.add(mi);
      }sorry to have to ask but I just can't seam to do it .
    Thanks
    Craig

Maybe you are looking for

  • Adobe Illustrator CS5 Setup Mistake (Clicked on "provide a serial number")

    Hi everyone, The instructions for installing Adobe Illustrator CS5 told me to to chose the option "Install this product as a trial" instead of "Provide a serial number" when I get to the "Enter a Serial Number" step.  I don't know why I was so stupid

  • Needed improvements to the panels

    Panel close buttons should be smaller, like one pixel only. Also, can the non-UI conforming icons be even more confusing and obscure, please?

  • IPod screen is white

    hello all! ive just been on holidays in spain and italy and used an ipod camea connector to store and transfer all my photos to my ipod (color display) and i stored about 3000 photos and now that ive arrived home, i plugged in my ipod and the screen

  • Text Variables in Report Designer

    We are creating some formatted reports in BI 7.0 using the Report Designer tool. One of the requirements is that when the report is flitered by a certain characteristic, say for e.g. Country = 'DE', the text associated with the country e.g. 'Germany'

  • Create Smart Collection for Photos Without Lens Profile Applied?

    The subject pretty much says it all. Is there any way to create a smart collection of photos that have not had lens profile corrections applied?