2012-01-28 52 views
0

startsWith(字符串前缀)需要两个字符串,并搜索,如果两个字符串都以相同的值开始,有没有办法修改startsWith(字符串前缀)来搜索一个字符串重新发生字符?可能的修改startsWith(字符串前缀)来搜索一个字符串重新发生字符?

比方说

String str = "MANAMA"; 

我希望能够搜索使用startsWith()和的endsWith()的字符串或一些变化,以确定该字符串的前缀或后缀是否是相同的。唯一的问题是这些方法查找两个字符串,看看他们是否有匹配后缀的或前缀的

startsWith(字符串前缀)没有这样的:

String str1 = "MANAMA"; 
    String str2 = "PANAMA."; 


    // Sets what characters to search for from above strings 
    String startStr = "MA"; 

    // Searchs for startStr in strings 
    boolean starts1 = str1.startsWith(startStr); 
    boolean starts2 = str2.startsWith(startStr); 

    // Display the results of the startsWith calls. 
    System.out.println(starts1); 
    System.out.println(starts2); 

的endsWith(字符串后缀)作用:

String str1 = "MANAMA"; 
String str2 = "PANAMA."; 


// Sets what characters to search for from above strings 
String endStr = "MA"; 

// Searchs for startStr in strings 
boolean ends1 = str1.endsWith(endStr); 
boolean ends2 = str2.endsWith(endStr); 

// Display the results of the endsWith calls. 
System.out.println(ends1); 
System.out.println(ends2); 

有没有办法修改或不同的方法能够搜索一个字符串,而不是搜索endStr和startStr的两个字符串?

+2

请发布您想要实现的示例。 – kosa 2012-01-28 07:55:42

+1

问题不明确。你能详细说明吗?举个例子? – 2012-01-28 07:57:16

+0

现在怎么样?编辑 – Enigma 2012-01-28 08:16:15

回答

1

不知道我是否正确理解你的问题,但你可以在同一个字符串上使用endsWith()startsWith()。例如:

String line = "MANAMA"; 
String edge = "MA"; 

boolean check = line.startsWith(edge) && line.endsWith(edge); 
// returns true if the string starts and ends with "MA" 
+0

是的,你可以在同一个字符串上调用'endsWith()'和'startsWith()'方法。 – Dawood 2012-01-28 08:29:07

+0

那么,如果我不知道字符串是什么,直到用户键入它,我将如何设置方法应该搜索的字符? – Enigma 2012-01-28 08:33:07

+0

我不认为我理解你的问题 - 你是不是指定要检查的前缀和后缀? – Dawood 2012-01-28 08:37:01