我需要将字符串中的字符序列放在括号中,这样它就会选择最长的子字符串作为放在括号中的最佳子字符串。因为太复杂,无法用语言解释,所以说清楚: 如果我的输入是:
'these are some chars *£&$'
'these are some chars *£&$^%(((£'
两个输入的输出分别应为:
'these are some chars (*£&$)'
'these are some chars (*£&$^%)(((£'
所以我想将序列 *£&$^% 放在括号中(如果它存在),否则将其放在括号中 *£&$ 我希望这是有道理的!
最佳答案
一般情况下,这个方法是有效的。它包围任何给定字符串中任何关键字的最早子字符串:
public String bracketize() {
String chars = ...; // you can put whatever input (such as 'these are some chars *£&$')
String keyword = ...; // you can put whatever keyword (such as *£&$^%)
String longest = "";
for(int i=0;i<keyword.length()-1;i++) {
for(int j=keyword.length(); j>i; j--) {
String tempString = keyword.substring(i,j);
if(chars.indexOf(tempString) != -1 && tempString.length()>longest.length()) {
longest = tempString;
}
}
}
if(longest.length() == 0)
return chars; // no possible substring of keyword exists in chars, so just return chars
String bracketized = chars.substring(0,chars.indexOf(longest))+"("+longest+")"+chars.substring(chars.indexOf(longest)+longest.length());
return bracketized;
}
嵌套的 for
循环检查 keyword
的每个可能的子字符串,并选择较大的 String
中包含的最长的子字符串,字符
。例如,如果关键字是 Dog,它将检查子字符串“Dog”、“Do”、“D”、“og”、“o”和“g”。它将这个最长的可能子字符串存储在longest
中(它被初始化为空字符串)。如果检查每个子串后longest
的长度仍然为0,则在chars
中找不到keyword
的子串,因此原始String ,字符,被返回。否则,将返回一个新字符串,该字符串是 chars
,其中子字符串 longest
被方括号(圆括号)括起来。
希望这有帮助,如果有效请告诉我。
关于java - 将括号添加到字符串中的字符序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19597357/