【发布时间】:2015-02-26 17:01:53
【问题描述】:
在我的程序中,我试图在“,”字符处分割一个字符串。拆分字符串后,我需要在“=”字符之后创建一个新字符串。然后我需要将字符串重建回原来的状态。目前我能够拆分字符串并将其重建为原始状态。但是,当我尝试使用 indexof 和 substring 方法创建一个新字符串时,我没有得到正确的字符串。我在下面列出了我的代码以及我当前的输出和我不想要的输出。提前感谢您的帮助。
public class StringTestProgram {
public static void main(String[] args) {
String relativeDN = "cn=abc,dn=xyz,ou=abc/def";
System.out.println(relativeDN);
//Split String
String[] stringData = relativeDN.split(",");
{
StringBuilder sb = new StringBuilder();
CharSequence charAdded = ",";
// loop thru each element of the array
for (int place = 0; place < stringData.length; place++) {
System.out.println(stringData[place]);
{
int eq = relativeDN.indexOf('=');
String sub = relativeDN.substring(0, eq);
System.out.println(sub);
}
// append element to the StringBuilder
sb.append(stringData[place]);
// avoids adding an extra ',' at the end
if (place < stringData.length - 1)
// if not at the last element, add the ',' character
sb.append(charAdded);
}
System.out.print(sb.toString());
}
}
}
我原来的字符串"cn=abc,dn=xyz,ou=abc/def"
我目前的输出:
cn=abc (split string)
cn (create new String)
dn=xyz (split string)
cn (create new String)
ou=abc/def (split string)
cn (create new String)
cn=abc,dn=xyz,ou=abc/def (rebuild String to its original form)
我想要的输出:
cn=abc (split string)
abc (create new string)
dn=xyz (split string)
xyz (create new String)
ou=abc/def (split string)
abc/def (create new String)
cn=abc,dn=xyz,ou=abc/def (rebuild String to its original form)
【问题讨论】:
标签: java string split substring indexof