gpt4 book ai didi

java - 使用 String split Java 重建字符串

转载 作者:行者123 更新时间:2023-12-01 15:22:18 25 4
gpt4 key购买 nike

我正在编写一个程序,它将获取乐谱(歌词上方的和弦)并调调。我选择拆分歌曲字符串,操作和弦名称并构建一个新字符串。我的方法是将歌曲分成几行 String[]holder = Song.split("\\n+"); 然后,取出每一行并根据空格进行分割 String[] oneLine = s.split("\\s");

构建新字符串时,保持原始间距绝对至关重要。我的问题是,通过分割//,我会丢失所有间距历史记录。谁能建议解决我的问题?

这是一首示例歌曲

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

目前我的转调歌曲看起来像这样......

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

最佳答案

如果您使用StringTokenizer来分割字符串,它也可以配置为保留并返回分隔符。这样,您就可以保持空格的数量。

请参阅StringTokenizer(String,String,boolean)构造函数。

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.

关于java - 使用 String split Java 重建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10730632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com