Results 1 to 3 of 3
  1. #1
    AcousticBruce is offline Senior Member
    Join Date
    Dec 2010
    Location
    Indiana
    Posts
    202
    Rep Power
    5

    Default Understanding String.length() with \n

    Java Code:
            String a = "37107287\n";
            String b = "37107287";
    
            System.out.println(a.length());
            System.out.println(b.length());
    Why does \n add to the length of a string?
    Is there a way find the length without /n added to it?

  2. #2
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    6

    Default

    the length considers all characters in the string. \n is a character, it just happens to be not printable and have special meaning to mean end of line

    if you wanted to get the length excluding the \n, you could do

    Java Code:
     String a = "37107287\n";
     System.out.println(a.trim().length());
    Where trim removes leading and following whitespace characters, which would also include spaces and tabs.

    Or in a more general case, if the string contains \n characters within it, or just exclude \n characters, use replaceAll to remove \n characters then take the length,

    Java Code:
     System.out.println(a.replaceAll("\\n","").length());
    where we need to escape \ in a string.

    [/code]

  3. #3
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default

    Why not? oO
    Its a char in the char-Array of the string. it must be stored somewhere or?

    System.out.println(a.replace("\n", "").length()); or in your example
    System.out.println(a.trim().length());

    edit: @travishein : why regex? ;/

Similar Threads

  1. String.length?
    By rizowski in forum New To Java
    Replies: 7
    Last Post: 11-20-2010, 06:33 PM
  2. string length HELP PLZ!!
    By vette427 in forum Eclipse
    Replies: 1
    Last Post: 09-23-2010, 07:12 AM
  3. Validating for length of String
    By Bascotie in forum New To Java
    Replies: 1
    Last Post: 10-11-2009, 12:45 PM
  4. Replies: 1
    Last Post: 01-14-2009, 06:19 PM
  5. [SOLVED] String Length issue.
    By ChrisMayhew in forum New To Java
    Replies: 7
    Last Post: 01-11-2009, 04:16 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •