代码之家  ›  专栏  ›  技术社区  ›  Tom

Java练习题

  •  1
  • Tom  · 技术社区  · 17 年前

    http://www.javabat.com/prob/p141494

    public String startWord(String str, String word) 
    {
    
     if (str.startsWith(word)){
         return str.substring(0, word.length());
     }
    
     if (str.substring(1, str.length()).equals(word.substring(1, word.length()))){
         return str.substring(0, word.length());
     }
    
     return "";
    }
    

    8 回复  |  直到 17 年前
        1
  •  3
  •   Sean    17 年前

        2
  •  2
  •   tvanfosson    17 年前

    在忽略第一个字符的情况下,您只想进行比较 word.length() - 1

    请注意,你真的不需要测试第一个字母完全匹配的情况,因为这是你忽略第一个字母的情况的一个子集。

        3
  •  2
  •   amischiefr    17 年前

    str.substring(1,word.length()).equals(word.substring(1,word.length()))
    
        4
  •  2
  •   Victor    17 年前

    你的想法是对的。..只需比较以下子字符串 怎么翻译 从角色1到 到的子字符串 从字符1到单词末尾。 如果它们匹配,则返回以下子字符串 怎么翻译 .

        5
  •  0
  •   laz    17 年前

    if (str.length() > 0 && str.substring(1).startsWith(word.substring(1))) {
    

    因为条件更为明确。此外,tvanfosson和Darth Eru是正确的,第一个与第一个字符完全匹配的条件是无关的。

        6
  •  0
  •   Carl Manaster    17 年前

    这是你的起点

    import junit.framework.TestCase;
    
    public class HippoTest extends TestCase {
    
        public void testActualStart() throws Exception {
            assertEquals("hi", startWord("hippo", "hi"));
        }
    
        public void testSimilarStart() throws Exception {
            assertEquals("xip", startWord("hippo", "hip"));
            assertEquals("h", startWord("i", "hip"));
        }
    
        public void testWrongStart() throws Exception {
            assertEquals("", startWord("hippo", "hx"));
        }
    
        private String startWord(String string, String string2) {
            // TODO Auto-generated method stub
            return null;
        }
    }
    

    如果你一次通过一个测试用例,也许这比试图一次解决整个问题更容易。

        7
  •  -2
  •   foobarfuzzbizz    17 年前

    对于1个字母长的字符串的边界情况,只需硬编码即可正确返回。

        8
  •  -2
  •   lud0h    17 年前

    试试正则表达式!

    java.lang.String
    
    boolean matches(String regex)