一些測驗用例不起作用。我可以知道我哪里錯了。測驗用例“我喜歡編程正在作業,但其他 idk 無法正常作業的測驗用例。
class Solution
{
public String transform(String s)
{
// code here
char ch;
// String s = "i love programming";
String res="";
ch = s.charAt(0);
ch = Character.toUpperCase(s.charAt(0));
res =ch;
for(int i=1;i<s.length();i ){
if(s.charAt(i) == ' '){
//System.out.println(i);
ch = Character.toUpperCase(s.charAt(i 1));
res =' ';
res =ch;
i ;
}else {
res =s.charAt(i);
}
}
return res;
}
}
//Some test cases are not working. May I know where I went Wrong?
uj5u.com熱心網友回復:
這個解決方案對我非常有效,所有測驗用例都通過了。謝謝你。
class Solution
{
public String transform(String s)
{
// code here
char ch;
// String s = "i love programming";
String res="";
ch = s.charAt(0);
ch = Character.toUpperCase(s.charAt(0));
res =ch;
for(int i=1;i<s.length();i ){
if(s.charAt(i-1) == ' '){
//System.out.println(i);
ch = Character.toUpperCase(s.charAt(i));
res =ch;
}else {
res =s.charAt(i);
}
}
return res;
}
}
uj5u.com熱心網友回復:
嘗試將空格后的下一個字符設為大寫(僅當此字符是字母且此字符可用時才應這樣做)。類似地,句子的第一個字符是大寫的,而不檢查第一個字母是否是字母。
最好使用布爾標志,在將大寫應用于字母時應重置該標志。此外,StringBuilder應該使用而不是在回圈中連接字串。
因此,改進后的代碼可能如下所示,并添加了更多規則:
- 使單詞中的第一個字母由字母和/或數字大寫
- 單詞用任何非字母/非數字字符分隔,除非
'用于收縮等I'm, there's。 - 檢查
null/空輸入
public static String transform(String s) {
if (null == s || s.isEmpty()) {
return s;
}
boolean useUpper = true; // boolean flag
StringBuilder sb = new StringBuilder(s.length());
for (char c : s.toCharArray()) {
if (Character.isLetter(c) || Character.isDigit(c)) {
if (useUpper) {
c = Character.toUpperCase(c);
useUpper = false;
}
} else if (c != '\'') { // any non-alphanumeric character, not only space
useUpper = true; // set flag for the next letter
}
sb.append(c);
}
return sb.toString();
}
測驗:
String[] tests = {
"hello world",
" hi there,what's up?",
"-a-b-c-d",
"ID's 123abc-567def"
};
for (String t : tests) {
System.out.println(t " -> " transform(t));
}
輸出:
hello world -> Hello World
hi there, what's up? -> Hi There,What's Up?
-a-b-c-d -> -A-B-C-D
ID's 123abc-567def -> ID's 123abc-567def
uj5u.com熱心網友回復:
我盡力理解你的代碼,因為格式在我假設的降價中有點被屠殺,但盡管如此,我還是認為這與你的解決方案很接近:
public class MyClass {
public static void main(String args[]) {
int i = 0;
String greet = "hello world";
String res = "";
res = Character.toUpperCase(greet.charAt(i ));
for (; i < greet.length(); i ){
if (greet.charAt(i) == ' '){
res = res greet.charAt(i) Character.toUpperCase(greet.charAt(i 1) );
i ;
}else{
res = greet.charAt(i);
}
}
System.out.println(res);
}
}
對我來說這是有效的,但這是假設空格只出現在單詞之間。也許您的問題的答案在于這些測驗用例,更重要的是這些測驗用例背后的假設。如果可以,請嘗試收集有關此的更多資訊:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/310991.html
標籤:爪哇
上一篇:如何在Java中獲取員工總數?
