Groovy在这里。我正在尝试迭代字符串中的字符,并使用以下逻辑将它们添加到另一个字符串:
" ${theChar}"
)
我最好的尝试并没有那么好:
// We want to convert this to: 'Well Hello There'
String startingStr = 'WellHelloThere'
String special = ''
startingStr.each { ch ->
if(ch == ch.toUpperCase() && startingStr.indexOf(ch) != 0) {
special += " ${ch}"
} else {
special += ch
}
}
更多例子:
Starting Str | Desired Output
======================================
'wellHelloThere' | 'well Hello There'
'WellHello9Man' | 'Well Hello 9 Man'
'713Hello' | '713 Hello'
我在这里出错的任何想法?
答案 0 :(得分:1)
尝试如下: -
String regex = "(?=\\p{Upper})|(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"
String s1 = 'wellHelloThere'
String s2 = 'WellHello9Man'
String s3 = '713Hello'
assert s1.split(regex).join(" ") == "well Hello There"
assert s2.split(regex).join(" ") == "Well Hello 9 Man"
assert s3.split(regex).join(" ") == "713 Hello"
答案 1 :(得分:0)
请考虑以下事项:(请参阅关于&#39; 713 Hello&#39;以及所述规则的所需输出的评论)
String s1 = 'wellHelloThere'
String s2 = 'WellHello9Man'
String s3 = '713Hello'
def isUpperCaseOrDigit = { it ==~ /^[A-Z0-9]$/ }
def convert = { s ->
def buffer = new StringBuilder()
s.eachWithIndex { c, index ->
def t = c
if ((index != 0) && isUpperCaseOrDigit(c)) {
t = " ${c}"
}
buffer.append(t)
}
buffer.toString()
}
assert "well Hello There" == convert(s1)
assert "Well Hello 9 Man" == convert(s2)
// this is different than your example, but conforms
// to your stated rules:
assert "7 1 3 Hello" == convert(s3)