0

I have a text file with string as follows

1.dfaf 2.agdagdag 3.dgdfg 4.sdfsasd 5.dfdf 6.gdg7.fadgd8.dsgg9.fgdsf 10.trete

I know the logic to read it from file and write to new file

but I want to know the logic to split it at numbers and write in new line in output file

like

1.dfaf
2. agdagdag
3. dgdfg

etc...

how to get it.

skalluri
  • 53
  • 1
  • 8

6 Answers6

1

If you only want to write and not store the new string, then you can use do the following. Simply replace the space character with a newline character! The newly created string will thus be in the exact format you want it to be written to the file.

  String orignalString = readFromFile(...); // implement this
  String stringToWriteToFile = originalString.replace(" ","\n"); // so you replace the space with a \n
  writeToFile(stringToWriteToFile); // implement this

This will work only if the strings are consistently separated by a single space.

Note: If this is homework, everybody will use String.split(). So you might get a few extra points for being innovative and using String.replace(). I did myself!

CodeBlue
  • 14,631
  • 33
  • 94
  • 132
0

Try String.split http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)

You'll need to learn a bit of regular expression to use it, but regex is a very good thing to learn.

veefu
  • 2,820
  • 1
  • 19
  • 29
0

String.split(Sting regex) would be a great place to start. Also, regular expressions would be a necessary additional piece to solving your question.

Makoto
  • 104,088
  • 27
  • 192
  • 230
0

You can use the String.split() method to do this:

String[] result = "1.dfaf 2.agdagdag 3.dgdfg 4.sdfsasd 5.dfdf 6.gdg7.fadgd8.dsgg9.fgdsf 10.trete".split("\\s");
for (int x = 0; x < result.length; x++) {
    System.out.println(result[x]);
}

You can also use a StringTokenizer to do this, but that seems to be discouraged.

Is that what you meant?

Conan
  • 2,288
  • 1
  • 28
  • 42
0

You should use the split function and make the delimiter a regex (Space followed by 1 digits)

This should do it...

String[] arr = "1.dfaf 2.agdagdag 3.dgdfg 4.sdfsasd 5.dfdf 6.gdg 7.fadgd 8.dsgg 9.fgdsf 10.trete".split(" ");
for(int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}
george_h
  • 1,562
  • 2
  • 19
  • 37
0

Perhaps this may help:

  • Once you have the string, finds all the substrings that matches with \d+\.[a-z]+. For that you need java.util.regex.Matcher and/or java.util.regex.Pattern. You can find an example in Test Harness (The Java™ Tutorials > Essential Classes > Regular Expressions). Look the methods matcher.find() and matcher.group().
  • Then you have to separate each substring by . with split if you want to insert a space between number and text.

I hope this can help. Good luck!

Paul Vargas
  • 41,222
  • 15
  • 102
  • 148