0

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
1
  • Do you mean from G Em C D you want to change to A F#m D E with the white-space before? But because you trying to change it than the white-space become disappear? Can you post the code when you trying to change the key? Commented May 24, 2012 at 3:54

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I've used the tokenizer before, but didn't realize it had this functinality. I'll give it a shot. Thanks!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.