Google Answers Logo
View Question
 
Q: Java method that will split up a string into pieces of equal size ( Answered,   1 Comment )
Question  
Subject: Java method that will split up a string into pieces of equal size
Category: Computers > Programming
Asked by: crom654-ga
List Price: $75.00
Posted: 30 Nov 2006 07:53 PST
Expires: 30 Dec 2006 07:53 PST
Question ID: 787008
I need a Java function that will take a string, and, if it is over
32k, split it up into pieces equaling 32k each (except the last one
which of course probably would not be 32k exactly).

Here is a method I have that splits up a string by line, then appends
each to a Lotus Notes rich text field. If you could send me a function
that demonstrates splitting of text by size, or edit this function so
it does this, that would be great.

I'll miss you, Google Answers!


public static void appendToRTItem(RichTextItem rTItem, String rTText)
throws Exception {
		int maxSize = 32000;
		int textLen = rTText.length();

		try {
			if (textLen > maxSize) {
				int si = 0;
				int ei = maxSize;

				while (si < textLen) {
					if (ei > textLen) ei = textLen;

					rTItem.appendText(rTText.substring(si, ei));
					si = ei;
					ei = ei + maxSize;
				}
			}
			else {
				rTItem.appendText(rTText);
			}
		}
		catch (NotesException e) {
			throw new Exception("RTItem can't append to it!");
		}
Answer  
Subject: Re: Java method that will split up a string into pieces of equal size
Answered By: leapinglizard-ga on 30 Nov 2006 12:17 PST
 
Dear crom654,


You will find below the full listing for Splitter.java, in which the
class Splitter has a method split() that does what you ask.

The default value for the maximum split length is 32*1024 -- this is
what programmers generally think of as 32k -- although you can set it
32000 or any other integer value by adjusting the constant
defaultMaxLen. You can also set the split length by calling the custom
constructor Splitter(int maxLen). This is what I have done in the
main() method, using a split length of 5 to run a little interactive
test on the command line. A sample transcript follows.


$ java Splitter
Testing with split length = 5
Please enter a string: hello
>>hello<<
 >hello< (5)

$ java Splitter
Testing with split length = 5
Please enter a string: hi
>>hi<<
 >hi< (2)

$ java Splitter
Testing with split length = 5
Please enter a string: The quick brown fox jumps over the lazy dog.
>>The quick brown fox jumps over the lazy dog.<<
 >The q< (5)
 >uick < (5)
 >brown< (5)
 > fox < (5)
 >jumps< (5)
 > over< (5)
 > the < (5)
 >lazy < (5)
 >dog.< (4)


I have included copious code comments to aid your understanding.

Regards,

leapinglizard


import java.lang.*;
import java.util.*;
import java.io.*;

public class Splitter {

    // the given string will be split into substrings no longer than maxLen
    private int maxLen;

    // the default constructor uses this value to initialize maxLen
    private static int defaultMaxLen = 32*1024;

    // default constructor: make new Splitter with default maxLen value
    public Splitter() {
        maxLen = defaultMaxLen;
    }

    // custom constructor: make new Splitter with specified maxLen value
    public Splitter(int maxLen) {
        this.maxLen = maxLen;
    }

    // accessor method: get the current maxLen value
    public int getMaxLen() {
        return maxLen;
    }

    // mutator method: set maxLen to specified value
    public void setMaxLen(int maxLen) {
        this.maxLen = maxLen;
    }


    // the real work gets done here:
    //   -- split the given string into substrings no longer than maxLen
    //   -- return as an array of strings
    public String[] split(String str) {

        // get the length of the original string
        int origLen = str.length();

        // calculate the number of substrings we'll need to make
        int splitNum = origLen/maxLen;
        if (origLen % maxLen > 0)
            splitNum += 1;

        // initialize the result array
        String[] splits = new String[splitNum];

        // for each substring...
        for (int i = 0; i < splitNum; i++) {

            // the substring starts here
            int startPos = i * maxLen;

            // the substring ends here
            int endPos = startPos + maxLen;

            // make sure we don't cause an IndexOutOfBoundsException
            if (endPos > origLen)
                endPos = origLen;

            // make the substring
            String substr = str.substring(startPos, endPos);

            // stick it in the result array
            splits[i] = substr;
        }

        // return the result array
        return splits;
    }


    public static void main(String[] argv) {
        int splitLen = 5;
        BufferedReader in = new BufferedReader(
                new InputStreamReader(System.in));
        String str = "";
        System.out.println("Testing with split length = "+splitLen);
        System.out.print("Please enter a string: ");
        try {
            str = in.readLine();
        } catch (IOException err) {
            System.out.println("IOException: "+err);
            System.exit(1);
        }
        System.out.println(">>"+str+"<<");
        String[] result = new Splitter(splitLen).split(str);
        for (int i = 0; i < result.length; i++)
            System.out.println(" >"+result[i]+"< ("+result[i].length()+")");
    }
}
Comments  
Subject: Re: Java method that will split up a string into pieces of equal size
From: pingraham-ga on 30 Nov 2006 15:05 PST
 
Comment re:leapinglizard's solution.  This solution naively assumes
one character = one byte.  This is correct most of the time, yes, but
will break for Unicode.  I don't know if that's an input you need to
deal with, but since particularly nasty Unicode characters may be 4
bytes long (Chinese ideograms and the like), I believe that this is
not guaranteed to produce 32K slices.  You will want to use the
function getBytes() here:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#getBytes()
It'll return a byte array which you can query the length of.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy