Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

File to string and parsing the string

Status
Not open for further replies.

KrisLake

Programmer
Feb 4, 2002
3
FI
I'm trying to read a txt file into string
and then cut the string into peaces,but it's
not quite working.

if the file looks like this:
this
is

atest

folks

String should be something like this: this is atestfolks
and after parsing

this
is a
test
folk
s

now it's putting all the lines together and i can't get lengt of the
firs word and parsing doesn't work right.

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

class New{

public static void main(String []args)throws IOException {
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));

StringBuffer sb=new StringBuffer();


File inputFile = new File ("help.txt");
FileReader fis =new FileReader(inputFile);
BufferedReader bis = new BufferedReader(fis);

for(String line=bis.readLine();line != null;line=bis.readLine()) {

sb.append(rivi);
line=line.trim();


}

String test=sb.toString();


Here i'll try to cut the string into equal length peaces
length is the length of the firs word in file. if i have to combine two words then add one space.

String tmp= "";
int spacefound=0;
int l=test.indexOf(" ");

for(int i=0;i<test.length();i++){
char c=test.charAt(i);
if(c!=' ') tmp+=&quot;&quot;+c;

if(c==' ' && (spacefound<1) && !(tmp.equals(&quot;&quot;))) {
tmp+=&quot;&quot;+c;
spacefound++;
}//if

if(tmp.length()==l) {
System.out.println(tmp);

tmp=&quot;&quot;;
spacefound=0;
}

}
if(tmp.length()<l){
for(int i=0;i<=(l-tmp.length());i++)
tmp+=&quot;&quot;+' ';
}//if


System.out.println(tmp);

}
}
 
hi

u neednt struggle so much to split the string. use the StringTokenizer class.

StringTokenizer st = new StringTokenizer(str,&quot; &quot;); //the str is the string u want to split, &quot; &quot; is the character u want to use as the split character.

for(;st.hasMoreTokens();)
{
System.out.println(st.nextToken());
}

this prints the tokens on the screen. u can take out the System.out thing and store the st.nextToken in some variable if u want. u can also change the splitting character from space to something else.


luv
Karthik.
Pearls and Diamonds are not found on surfaces.
 
I've tried with stringTokenizer
but it spilts the string every time
space it met!
and i'm trying to cut the string
every time the length of the first
word is reached

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top