简体   繁体   中英

Split the string at numbers and write in the output file in java

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.

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!

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.

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

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?

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]);
}

Perhaps this may help:

  • Once you have the string, finds all the substrings that matches with \\d+\\.[az]+ . 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM