dh762
dh762

Reputation: 2428

Split a String in an ArrayList depending on selected amount of characters

I'd like to split a string into an ArrayList. Example:

String = "Would you like to have responses to your questions" result with amount 3: Wou -> arraylist, ld -> arraylist, you -> arraylist, ...

the amount is a predefined variable.

so far:

public static void analyze(File file) {

    ArrayList<String> splittedText = new ArrayList<String>();

    StringBuffer buf = new StringBuffer();
    if (file.exists()) {
        try {
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis,
                    Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(isr);
            String line = "";
            while ((line = reader.readLine()) != null) {
                buf.append(line + "\n");
                splittedText.add(line + "\n");
            }
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String wholeString = buf.toString();

    wholeString.substring(0, 2); //here comes the string from an txt file
}

Upvotes: 1

Views: 1141

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198361

The "normal" way to do it is about what you'd expect:

List<String> splits = new ArrayList<String>();
for (int i = 0; i < string.length(); i += splitLen) {
  splits.add(string.substring(i, Math.min(i + splitLen, string.length()));
}

I'll throw out a one-line solution with Guava, though. (Disclosure: I contribute to Guava.)

return Lists.newArrayList(Splitter.fixedLength(splitLen).split(string));

FYI, you should probably use StringBuilder instead of StringBuffer, since it doesn't look like you need thread safety.

Upvotes: 2

anubhava
anubhava

Reputation: 785751

You can do it without substring calls like this:

String str = "Would you like to have responses to your questions";
Pattern p = Pattern.compile(".{3}");
Matcher matcher = p.matcher(str);
List<String> tokens = new ArrayList<String>();
while (matcher.find())
    tokens.add(matcher.group());
System.out.println("List: " + tokens);

OUTPUT:

List: [Wou, ld , you,  li, ke , to , hav, e r, esp, ons, es , to , you, r q, ues, tio]

Upvotes: 1

Drake Clarris
Drake Clarris

Reputation: 1045

You are adding each line to your array list, and it doesn't sound like that is what you want. I think you are looking for something like this:

int i = 0;
for( i = 0; i < wholeString.length(); i +=3 )
{
    splittedText.add( wholeString.substring( i, i + 2 ) );
}
if ( i < wholeString.length() )
{
    splittedText.add( wholeString.substring( i ) );
}

Upvotes: 0

Related Questions