Loading...
Logo
Processing Forum

Text question

in Programming Questions  •  1 year ago  
I am splitting a text file into sentences, which I then want to be able to display individually.

I'm splitting into sentences this way:

String[] paragraphs;

void setup(){
  paragraphs = loadStrings("article.txt");

  for (int j=0; j<paragraphs.length; j++) {
    String sentences[] = split(paragraphs[j], '.');

  println(sentences[j]);
    }
  }

This removes the period and also includes the space between sentences at the beginning of each sentence,
so instead of 
"The dog ran."
I have
" The dog ran"

I know how to add the period back in, but is there an easy way to remove that space at the beginning, or keep it from being included in the first place?

Replies(4)

Re: Text question

1 year ago
If 0 or 1 leading spaces, this works:

if (t.charAt(0) == ' ')
  t = t.substring(1);


If 0,1 or 2+ leading spaces, this works:

while (t.charAt(0) == ' ')
  t = t.substring(1);

Re: Text question

1 year ago
I updated to this, but I get a String Index Out Of Bounds Exeption. What am I doing wrong?

String[] paragraphs;
String[] sentences;

void setup() {
  paragraphs = loadStrings("article.txt");

  for (int j=0; j<paragraphs.length; j++) {
    sentences = split(paragraphs[j], '.');

    for (int i=0; i<sentences.length; i++) {
      String t = sentences[i];
      if (t.charAt(0) == ' ')
        t = t.substring(1);
      println(t);
    }
  }
}

Re: Text question

1 year ago
String t = sentence.trim();

Re: Text question

1 year ago
Worked perfectly! Thanks.