Formating String To Paragraph Format

Q

questionmarc420

Hi,
I've been working all week on trying to make these strings ( large
blocks of news) into a nice paragraph format. this is what ihave so
far.

String data_body = data.getBody();
data_body = data_body.replaceAll("\n\n","<br><br>");


i can't do a single /n wiht a single <br> becuase then it becomes
double spaced.
If anyone knows how ic an format these strings into a well formed
paragraph please let me know.

-morc
 
Q

questionmarc420

just to give an example of the string.
<code>
News Editors

VANCOUVER, British Columbia--(BUSINESS WIRE)--Jan. 20, 2006--
Anglo Swiss Resources Inc. (TSX
VENTURE:ASW)(OTCBB:ASWRF)(BERLIN:AMO) has entered into an agreement
with Impala Resources Inc., a private B.C. company, whereby Anglo
Swiss has acquired a 100-per-cent interest to 4 strategically located
mineral claims (UL 1&amp;2 and AFR 6&amp;7), covering approximately
10,330
acres situated within the diamond producing area of Lac de Gras, NWT.

Two of the claim groups are located within the newly penned
"Ekati Trend" approximately 40 kilometres northeast of the Ekati
diamond mine; and two claims are located 35 kilometers south of the
DO27 diamondiferous kimberlite currently the focus of detailed
exploration by Peregrine Diamonds et al. The company's new claims
cover kimberlite indicator minerals (KIM) anomalies and airborne
geophysical anomalies which require further work to prioritize drill
targets.

Anglo Swiss will continue to evaluate other diamond properties
within the Lac de Gras/Slave Craton area that meet its acquisition
criteria. Anglo Swiss has since June of 2005, positioned itself as
the majority holder of over 170,000 acres of claims of merit in under
explored areas with unexplained kimberlite indicator mineral trains
and/or kimberlite targets near known kimberlites and diamond mining
operations.

Anglo Swiss has with this announcement acquired a majority
interest in four projects which meet the acquisition criteria:

The Fry Inlet Diamond property consists of two adjacent
properties located near Lac de Gras and lie approximately 60
kilometres north of the Ekati diamond mine, and 90 kilometres north
of the Diavik diamond mine, Canada's first two diamond mines. These
claim groups total 91,856 acres and host the LI 201 diamondiferous
kimberlite. A technical report with further exploration
recommendations has been filed on this property and is available on
SEDAR. Work programs will commence this winter.

The MS 1-25 claim group covers approximately 52,459 acres in the
diamond producing area of Lac de Gras, NWT. This acquisition is
located approximately 35 kilometres southeast of the Diavik diamond
mine and is proximal to the DO-27 kimberlite currently the focus of
detailed exploration by Peregrine Diamonds et al. The MS claims cover
kimberlite indicator minerals (KIM) anomalies and airborne
geophysical anomalies which require further work to prioritize drill
targets this year.

The Fishing Lake Diamond property lies about 110 kilometres north
of Yellowknife, NWT, toward the western margin of the Slave Craton.
The Fishing Lake property covers 16,631 acres and covers a region
containing the probable source area for kimberlite indicator mineral
trains identified during the first stage of exploration for diamonds
on the Slave Craton in the mid 1990's. Work programs will commence
this winter.

These five claim groups total over 170,000 acres and are the
probable source areas for unresolved KIM trains and include known
diamondiferous kimberlite and numerous anomalies which warrant
additional exploration. Anglo Swiss is currently compiling new and
existing information from public and private sources for these claims
to better prioritize further exploration, drill targets and bulk
sampling.

In light of the close proximity to producing diamond mines, the
presence of numerous diamondiferous kimberlites and KIMs, management
is of the opinion that these properties are highly prospective for
the further discovery of diamonds and that the acquisition of these
claims significantly enhances the company's property position in the
Lac de Gras region.

The acquisition of the four additional claims is subject to
exchange approval and requires the Company to make cash payments
totalling $12,500 and issuing one million shares of Anglo Swiss to
the vendor. The vendor retain a 2-per-cent gross overriding royalty
(GORR) on any diamond production, of which the company may purchase 1
per cent point for $1.0-million. A kimberlite discovery bonus is
included by which the Company will pay to the vendor 200,000 common
shares for each new kimberlite discovered, to a maximum of two
million shares.

McAllister Property, South-east British Columbia

In lieu of the Company's major focus on the Lac de Gras region
for diamond exploration the Company has retained 8 mineral claims
(4,840 acres) in southeastern British Columbia for diamond
exploration. The main focus of the McAllister property is the
McAllister Diatreme, identified as the host of a potential
diamondiferous lamproite. The Company will re-assess the merits of
this property within the current exploration year.

On behalf of the Board,

"Len Danard", President & CEO

THE COMPANY RELIES ON LITIGATION PROTECTION FOR "FORWARD LOOKING"
STATEMENTS.



THE TSX VENTURE EXCHANGE HAS NOT REVIEWED AND DOES NOT ACCEPT REPO
NSIBILITY FOR THE ADEQUACY OR ACCURACY OF THIS RELEASE.

Anglo Swiss Resources Inc. (TSX VENTURE:ASW) (OTC Bulletin
Board:ASWRF) (BERLIN:AMO)



KEYWORD: NORTH AMERICA NEW YORK UNITED STATES CANADA
INDUSTRY KEYWORD: NATURAL RESOURCES MINING/MINERALS MERGER/ACQUISITION
SOURCE: Anglo Swiss Resources Inc.


CONTACT INFORMATION:
Anglo Swiss Resources Inc.
Len Danard
President &amp; CEO
(604) 683-0484
Fax: (604) 683-7497
(e-mail address removed)
www.anglo-swiss.com
</code>
how ever when placed in an the jsp file. it has no formating what so
ever. i can't use <pre> tags bcuz i need it to go to the full length of
the page.
 
Q

questionmarc420

that was a bad example. for instance in most of hte strings there is
not 2 /n. just one which would make a new paragrapgh look like this :

blahblahblahkfjjdkladsjfkljaldafjkajdaa.
new paragragh.

instead of:
blahblahblahkfjjdkladsjfkljaldafjkajdaa.

new paragragh.

which is making it hard for me to format to all string needs.
 
D

David Wahler

that was a bad example. for instance in most of hte strings there is
not 2 /n. just one which would make a new paragrapgh look like this :

blahblahblahkfjjdkladsjfkljaldafjkajdaa.
new paragragh.

instead of:
blahblahblahkfjjdkladsjfkljaldafjkajdaa.

new paragragh.

which is making it hard for me to format to all string needs.

This is more of an algorithms question than a Java question, but
anyway, how about something like this (in pseudocode):

for each line of the string:
check the indentation level
(i.e. number of leading spaces)
if (the line is completely empty OR
the line is indented more than the previous one):
then start a new paragraph
print out the line

Hope this helps.

-- David
 
R

Roedy Green

I've been working all week on trying to make these strings ( large
blocks of news) into a nice paragraph format. this is what ihave so
far.

I am not quite sure what your problem is. If you want to reflow the
text to a new line length and insert line breaks, you can do this:

// com.mindprod.reflow.Reflow.java
package com.mindprod.reflow;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;

/**
* Reflows lines into paragraph.
* with lines about the same length
* paragraphs separated by a single blank line.
*
* usage: java com.mindprod.reflow.Reflow file.txt
* copyright (c) 2003-2006 Roedy Green, Canadian Mind Products
* #327 - 964 Heywood Avenue
* Victoria, BC Canada V8V 2Y5
* tel: (250) 361-9093
* http://mindprod.com
*
* Source and excutables may be freely used for any purpose except
military.
*/
public class Reflow
{

/**
* Max line length of output. ideally would be
* configurable.
*/
public static int LINELENGTH = 60;

private static final String EmbeddedCopyright =
"copyright (c) 2003-2006 Roedy Green, Canadian Mind Products,
http://mindprod.com";

// input "before" file
static String inFilename;
static File inFile;
static BufferedReader inReader;

// output "after" file, the temporary, later renamed to match the
input
static String outFilename;
static File outFile;
static PrintWriter outWriter;

/**
* Command line utility to reflow the text.
*/
public static void main( String[] args )
{
try
{

analyseCommandLine(args);

openInReader(); /* Open input "before" file. */
/* Make sure file exists before */
/* song and dance about extension. */

openOutWriter(); /* open output "after" file */

System.out.println("Reflowing " + inFilename );

/* copy inReader to outWriter reglowing the text */
processFiles();

/* Rename output to input */
inReader.close();
outWriter.close();
inFile.delete();
outFile.renameTo(inFile);
// don't delete outFile, it has been renamed to a real file

}
catch ( IOException e )
{
System.out.print("Oops! IO failure. e.g. out of disk space.
\n");
die();
}

} // end main

/**
* analyse the command line. It should have a filename
* case insensitive.
*/
static void analyseCommandLine(String[] args)
{
if ( args.length != 1 )
{
banner();
System.out.println("Oops! usage: com.mindprod.reflow.Reflow
Myfile.txt \n");
die();
}

inFilename = args[0]; /* file to convert */
} // end analyseCommandLine

/**
* display a banner about the author
*/
static void banner()
{
/* Usually not displayed, just embedded. */

System.out.println("\n°±²Û Reflow 1.0 Û²±°"
+ "\nFreeware to reflow text."
+ "\ncopyright (c) 2003-2006 Roedy Green,
Canadian Mind Products"
+ "\n#327 - 964 Heywood Avenue, Victoria, BC
Canada V8V 2Y5"
+ "\nTelephone: (250) 361-9093
Internet:[email protected]"
+ "\nMay be used freely for non-military use
only\n\n");

} // end banner

/**
* open the input "before" file
*/
static void openInReader()
{
try
{
inFile = new File(inFilename);
if ( !inFile.exists() )
{
banner();
System.out.print("Oops! Cannot find file ");
System.out.println(inFilename);
die();
}
if ( !inFile.canRead() )
{
banner();
System.out.print("Oops! no permission to read (i.e.
examine) the file ");
System.out.println(inFilename);
die();
}
if ( !inFile.canWrite() )
{
banner();
System.out.print("Oops! no permission to write (i.e.
change) the file ");
System.out.println(inFilename);
die();
}

inReader = new BufferedReader(new FileReader(inFile), 4096 /*
buffsize */);
}
catch ( FileNotFoundException e )
{
banner();
System.out.print("Oops! Cannot open file ");
System.out.println(inFilename);
die();
}
} // end openInReader

/**
* open the output "after" file
*/
static void openOutWriter()
{

try
{
// get a temporary file in the same directory as inFile.
outFile = createTempFile("Reflow", "tmp", inFile);
outWriter = new PrintWriter(
new BufferedWriter(
new
FileWriter(outFile), 4096 /* buffsize */),
false /* auto flush */);
}
catch ( IOException e )
{
System.out.println("Oops! Cannot create the temporary work
file\n");
die();
}

} // end OpenOutWriter

/**
* Create a temporary file,
* Slightly smarter version of File.createTempFile
*
* @param prefix beginning letters of filename
* @param suffix ending letters of filename.
* @param near directory where to put file, or file to
* place this temp file near in the same directory.
* null means put the temp file in the
* current directory.
* @return A temporary file. It will not automatically
* delete on program completion, however.
* @exception IOException
*/
public static File createTempFile ( String prefix , String suffix ,
File near ) throws IOException {
if ( near != null )
{
if ( near.isDirectory () )
{
return File.createTempFile ( prefix, suffix, near );
}
else if ( near.isFile () )
{
String parent = near.getParent();
if ( parent != null )
{
File dir = new File( parent );
if ( dir.isDirectory () )
{
return File.createTempFile ( prefix, suffix, dir );
}
}
}
}
// anything else, just create in the current directory.
return File.createTempFile ( prefix, suffix );
}

/**
* copy inReader to outWriter, reflowing
* Presume files already open. Does not close them.
*
* @exception IOException
*/
static void processFiles() throws IOException
{

// list of words in paragraph
ArrayList words = new ArrayList(149);

// have we just seen an new line.
// blank lines separate paragraphs
boolean recentNL = false;

// the currernt word we are building up.
StringBuffer word = new StringBuffer( 50 );
try
{
charReadLoop:
while ( true )
{
int c = inReader.read();
if ( c < 0 ) break charReadLoop;
switch ( c )
{
case 160:
case ' ':
case '\t':
if ( word.length() != 0 )
{
words.add( word.toString() );
word.setLength( 0 );
}
break;

case '\n':
if ( word.length() != 0 )
{
words.add( word.toString() );
word.setLength( 0 );
}

if ( recentNL )
{
emitParagraph( words, LINELENGTH );
words = new ArrayList(149);
recentNL = false;
}
else
{
recentNL = true;
}
break;

case '\r':
/* dos has \r\n, unix just \n */
/* we just ignore them here and generate them as
needed on \n. */
break;

default:
/* ordinary non-blank char */
recentNL = false;
word.append( (char) c );
break;

} /* end switch */
} /* end while */

// dump possible last paragraph without trailing blank line.
if ( words.size() != 0 )
{
emitParagraph( words, LINELENGTH );
}
} // end try
catch ( EOFException e )
{

}
} // end processFiles

/**
* emits paragraph followed by blank line.
*
* @param words Array list of words to output
* @param maxLineLength
* maximum line length. If a word is longer
* it will not be split.
*/
static void emitParagraph ( ArrayList words, int maxLineLength )
{
/* if paragraph empty, nothing to do */
if ( words.size() == 0 )
{
return;
}
int lineLength = 0;
for ( Iterator iter = words.iterator(); iter.hasNext(); )
{
String word = (String) iter.next();
if ( lineLength + word.length() + 1 > maxLineLength )
{
// won't fit. Start a new line.
if ( lineLength != 0 )
{
outWriter.println();
lineLength = 0;
}
// no lead space
}
else
{
/* will fit */
if ( lineLength != 0 )
{
// add lead space
outWriter.print( ' ' );
lineLength++;
}
}
outWriter.print( word );
lineLength += word.length();

} // end for

outWriter.println();
outWriter.println();
}
/**
* make a noise
*/
static void honk()
{
java.awt.Toolkit.getDefaultToolkit().beep();
} // end honk

/**
* abort the run, clean up as best as possible.
*/
static void die()
{
honk();
try
{
if ( inReader != null ) inReader.close();
if ( outWriter != null ) outWriter.close();
}
catch ( IOException e )
{

}
System.exit(1); /* exit with errorlevel = 1 */
} // end die

} // end class Reflow
 
R

Roedy Green

I've been working all week on trying to make these strings ( large
blocks of news) into a nice paragraph format. this is what ihave so
far.

In HTML, normally you separate paragraphs with <p> or enclose them in
<P></p>.

If you just want to start a new line use <br>
 
R

Roedy Green

data_body = data_body.replaceAll("\n\n","<br><br>");

what about data_body = data_body.replaceAll("\n\n","<p>");
or
data_body = data_body.replaceAll("\n\n","</p><p>");
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top