Results 1 to 12 of 12
  1. #1
    innovo is offline Member
    Join Date
    Jul 2015
    Posts
    84
    Rep Power
    0

    Default how to Split a string?

    EDIT: I have no idea why but now all the java code is the same color as the text

    So far I have a string that I am reading from a file, but I want to split the string each time there is a comma. I looked up how to cut a string into strings and I got this basically
    Java Code:
    String[] parts = string.split(","); 
                    String part1 = parts[0]; // 004
                    String part2 = parts[1]; // 034556
    this is fine and dandy, as well as apparently legal to do in Java. However when integrating it into my current code I don't quite understand how to do this. I can't get the string to split at the commas. I get no error message which indicates to me that
    Java Code:
    String[] parts = string.split(",");
                    String part1 = parts[0]; // 004
                    String part2 = parts[1]; // 034556
    isn't connected to anything. The thing I don't understand is how to connect the above segment with the existing code I have now. How am I supposed to put this into my program?
    Java Code:
    public class Csvreader {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            String fileName = "Kit Serial Numbers TEMPLATE.csv";
            File file = new File(fileName);
            
           // Scanner inputStream = new Scanner(fileName);
            // TODO code application logic here
            try{
                Scanner inputStream = new Scanner(file);
                while(inputStream.hasNext()){
                    String data = inputStream.next();
                    System.out.println(data);
                    String string = data;
                    String[] parts = string.split(",");
                    String part1 = parts[0]; // 004
                    String part2 = parts[1]; // 034556
                    
                    
                }
                inputStream.close();
            }
       
            catch(FileNotFoundException e){
                System.out.printf("YOU DUN MESSED IT UP");
              //  e.printStackTrace;
            }
        }
        
    }
    Last edited by innovo; 07-15-2015 at 06:47 PM.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: how to Split a string?

    If your input data is

    004,034556

    then what you did above should work. The default delimiter for input (white space) and the next() method may cause problems if there are embedded spaces in your input. You need to read about the String class and Scanner class and write some test programs to ensure you understand the issues.

    Regards,
    Jim


    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: how to Split a string?

    How am I supposed to put this into my program?
    The split() method creates an array holding the tokens from the String. There is no need to copy the values from the array to other Strings. The code should use the length of the array to control how it accesses the elements in the array. For example if the length = 1, there won't be an element at index = 1

    What is the program supposed to do with the Strings that are split from the input String?
    If you don't understand my response, don't ignore it, ask a question.

  4. #4
    innovo is offline Member
    Join Date
    Jul 2015
    Posts
    84
    Rep Power
    0

    Default Re: how to Split a string?

    Quote Originally Posted by Norm View Post
    The split() method creates an array holding the tokens from the String. There is no need to copy the values from the array to other Strings. The code should use the length of the array to control how it accesses the elements in the array. For example if the length = 1, there won't be an element at index = 1

    What is the program supposed to do with the Strings that are split from the input String?
    a very good point, it can be possible that I'm simply not printing the output. I'll attempt that and see what happens.

  5. #5
    innovo is offline Member
    Join Date
    Jul 2015
    Posts
    84
    Rep Power
    0

    Default Re: how to Split a string?

    Okay so I ran it and it partly worked. It got the first word that was comma delimited but everything after that was ignored

    this was what Java was telling me after running the program

    "category" is part of the csv file I'm trying to read.

    category
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at csvreader.Csvreader.main(Csvreader.java:36)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)

  6. #6
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: how to Split a string?

    Yes, so what is on Csvreader.java line 36?
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: how to Split a string?

    For debugging, the Arrays class's toString() method will show what is in an array:
    Java Code:
      System.out.println("an ID "+ java.util.Arrays.toString(theArrayName));
    If you don't understand my response, don't ignore it, ask a question.

  8. #8
    innovo is offline Member
    Join Date
    Jul 2015
    Posts
    84
    Rep Power
    0

    Default Re: how to Split a string?

    Quote Originally Posted by gimbal2 View Post
    Yes, so what is on Csvreader.java line 36?
    String part2 = parts[1]; // 034556

  9. #9
    innovo is offline Member
    Join Date
    Jul 2015
    Posts
    84
    Rep Power
    0

    Default Re: how to Split a string?

    Quote Originally Posted by Norm View Post
    For debugging, the Arrays class's toString() method will show what is in an array:
    Java Code:
      System.out.println("an ID "+ java.util.Arrays.toString(theArrayName));
    I found that the problem was that the csv file had spaces in it. I am now able to successfully able to read the first row of the csv file via
    String part1 = parts[0];
    all the way to
    String part25= parts[24];


    So the only thing I have to figure out is how to read the other rows I guess. Probably something to do with \n

  10. #10
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: how to Split a string?

    Me personally: I always use a BufferedReader to eat through a file line by line. But in the case of a CSV file, I would just use a pre-existing CSV parser. CSV files tend to be more difficult to read than you think as they may involve quoted data for example.

    Java Code:
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(put_file_here));
    
    try{
      String line = null;
    
      while((line = reader.readLine()) != null){
    
        // do things and stuff with this line
      }
    } finally {
      reader.close();
    }
    Last edited by gimbal2; 07-16-2015 at 03:18 PM. Reason: do the right thing: always add resource closure code
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  11. #11
    innovo is offline Member
    Join Date
    Jul 2015
    Posts
    84
    Rep Power
    0

    Default Re: how to Split a string?

    Quote Originally Posted by gimbal2 View Post
    Me personally: I always use a BufferedReader to eat through a file line by line. But in the case of a CSV file, I would just use a pre-existing CSV parser. CSV files tend to be more difficult to read than you think as they may involve quoted data for example.

    Java Code:
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(put_file_here));
    
    try{
      String line = null;
    
      while((line = reader.readLine()) != null){
    
        // do things and stuff with this line
      }
    } finally {
      reader.close();
    }
    Wouldn't you need catch after try? Or is catch only for throw?

    Also regarding line 8 would I just put my regular code in there starting with line 13 of my code?

  12. #12
    Xen
    Xen is offline Member
    Join Date
    Jan 2015
    Posts
    86
    Rep Power
    0

    Default Re: how to Split a string?

    Quote Originally Posted by innovo View Post
    Wouldn't you need catch after try? Or is catch only for throw?
    A try without catch but with a finally block will probably just pass the exceptions on to the enclosing block, while ensuring that the finally block (the reader.close()) is executed. So while it does not process the exceptions (escalating, throwing them on) it still provides a means to write closing code the moment an exception does occur.

    Also regarding line 8 would I just put my regular code in there starting with line 13 of my code?
    Your Scanner probably divides up the string (stream) into pieces (like a tokenizer) and it does this by default using whitespace (which is spaces, tabs, newlines, and so on) according to the documentation. I never used it before, nice to know it exists.

    (There is also a java.util.StreamTokenizer, for what it's worth).

    If you don't care about breaking up the strings you read into real digestable 'tokens' such as numerals (numbers) and words and so on, and you just want to split your strings into components, then you don't need the Scanner at this point.

    Question this: will you need the Scanner after breaking up your lines into segments based on the comma separation (split)???

    A scanner can never work on the split strings (not easily at least) sinced it operates (by default, most likely) on a stream and after you've read some lines (e.g. using a BufferedReader) and you have split them with your splitting code, you will be left with Strings and no longer a stream. You need another way to digest what you get from the split strings (most likely your comma-separated values) ------ ON THE OTHER HAND.

    You can probably set your Scanner to ALSO BREAK ON COMMA's which would allow you to easily retrieve values without the splitting code.

    However I am mistaken about the Stream thing, you can perfectly put a Scanner onto a String without requiring the String to be turned into a StringReader. This will require you to create a new Scanner for every String though, which is a bit ... wasteful to say the least.

    The Scanner tokenizes your input stream based on a whitespace pattern. You can change the pattern.

    However, I do not know how to use this method:

    Java Code:
    public Scanner useDelimiter(String pattern)
    Just a little reason to dive into the descriptions of the classes you use. Study a bit. It will help you.
    Last edited by Xen; 07-26-2015 at 12:14 AM.

Similar Threads

  1. String split help
    By MiddleBlocker in forum New To Java
    Replies: 4
    Last Post: 03-11-2011, 02:57 AM
  2. Split a String with split()--Help
    By danilson in forum New To Java
    Replies: 7
    Last Post: 11-19-2010, 04:08 PM
  3. string split
    By gisler in forum New To Java
    Replies: 6
    Last Post: 12-17-2009, 02:23 PM
  4. How to split a String using split function
    By Java Tip in forum java.lang
    Replies: 4
    Last Post: 04-17-2009, 08:27 PM
  5. How to split a String using split function
    By JavaBean in forum Java Tip
    Replies: 0
    Last Post: 10-04-2007, 09:32 PM

Posting Permissions

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