I imported a TXT file into Processing. I would like to replace the line breaks from the imported text file with spaces. Is this possible using Processing?
1 Answers
A couple of things... Since you imported a txt file, I guess with the loadStrings() method I assume you are left with an array of Strings. You could now mean two things, either to join the array into one String or to actually find and replace the line breaks (or a combination). Lets see both possibilities.
First I will assume a similar String array as loadStrings() gives you:
String [] importedText = {"aaaa bbb","cccc dddd","eeee ffff gggg"};
If you want to join this array up to one single String, you iterate over your array and add the elements to another String like so:
String singleLineText = "";
for(int i = 0;i < importedText.length; i++) {
singleLineText += importedText[i] + " ";
}
This is the simplest and less confusing way to do it, unless you have a huge array of Strings and you are after performance (a debatable matter these days) where you can use the StringBuilder like this:
StringBuilder strb = new StringBuilder();
for(int i = 0;i < importedText.length; i++) {
strb.append(importedText[i]);
strb.append(" ");
}
String singleLineText = strb.toString();
If on the other hand you are truly after removing the line breaks then I apologize for the useless prologue and here is the way: There are two types of line breaks (two characters), you have to account for: line-feed(\n) and carriage-return(\r). You need to account for both because different operating systems use different breaks. So now lets suppose a String like this:
String lineWithBreaks = "aaaa\nbbbbb\rcccc\n\rddddd";
as well as our two breaks:
String linefeed = "\n";
String carriagereturn = "\r";
The method to remove the breaks is this:
lineWithBreaks = lineWithBreaks.replace(linefeed," ");
lineWithBreaks = lineWithBreaks.replace(carriagereturn," ");
where essentially you replace the two set Strings with a space character " "!

- 1
- 1

- 2,790
- 1
- 14
- 20