简体   繁体   中英

Rebuilding String with String split Java

I'm writing a program that will take sheet music (chords above lyrics) and transpose the key. I'm choosing to split up a song String, manipulate the chord names and build a new String. My approach is to split the song into lines String[] holder = song.split("\\\\n+"); Then, take each line and split based on whitespace String[] oneLine = s.split("\\\\s");

When building the new string, maintaining the original spacing is absolutely crucial. My problem is that by splitting on //s I lose all history of spacing. Can anyone suggest a solution to my problem?

Here is an example song

String song = "G   Em  C   D\nSome Lyrics Go Here\nG   C   D\nOther Lyrics Go Here";

Currently my transposed song would look like this...

AF#mDE
Some Lyrics Go Here
ADE
Other Lyrics Go Here

If you use a StringTokenizer to split the string, it can be configured to retain and return the delimiters as well. This way, you can maintain the number of spaces.

See the StringTokenizer(String,String,boolean) constructor.

public StringTokenizer(String str, String delim, boolean returnDelims)

Constructs a string tokenizer for the specified string. All characters in the delim argument are the delimiters for separating tokens.

If the returnDelims flag is true, then the delimiter characters are also returned as tokens. Each delimiter is returned as a string of length one. If the flag is false, the delimiter characters are skipped and only serve as separators between tokens.

Note that if delim is null, this constructor does not throw an exception. However, trying to invoke other methods on the resulting StringTokenizer may result in a NullPointerException.

Parameters:
str - a string to be parsed.
delim - the delimiters.
returnDelims - flag indicating whether to return the delimiters as tokens.

Instead of using String.split() which, as you have noticed, will discard your spacing, you'll need to use some other technique. You can simply process each line one character at a time in a loop, appending each character as its it processed to a StringBuilder , such that you end up with the same number of characters altogether at the end.

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