Given a string, return true if the first instance of “x” in the string is immediately followed by another “x”.
doubleX(“axxbb”) → true
doubleX(“axaxax”) → false
doubleX(“xxxxx”) → true
indexOf()定位子字符串在字符串首次出现位置
startsWith()是否以子字符串开头,return true or false
boolean doubleX(String str) {
int i=0;
str+="x";
while(str.charAt(i)!='x'){i++;}
if(i<str.length()-2 && str.charAt(i+1)=='x') return true;
else return false;
}
/*****************************************************/
boolean doubleX(String str) {
int i = str.indexOf("x");
if (i == -1) return false; // no "x" at all
// Is char at i+1 also an "x"?
if (i+1 >= str.length()) return false; // check i+1 in bounds?
return str.substring(i+1, i+2).equals("x");
// Another approach -- .startsWith() simplifies the logic
// String x = str.substring(i);
// return x.startsWith("xx");
}
Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so “hixxxhi” yields 1 (we won’t count the end substring).
last2(“hixxhi”) → 1
last2(“xaxxaxaxx”) → 1
last2(“axxxaaxx”) → 2
public int last2(String str) {
int n=str.length()-1;
int count=0;
if(n>2){
String last = str.substring(n-1);
for(int i=0;i<n-1;i++)
if(str.substring(i).startsWith(last)) count++;
}
return count;
}
/********************************************************/
public int last2(String str) {
// Screen out too-short string case.
if (str.length() < 2) return 0;
String end = str.substring(str.length()-2);
// Note: substring() with 1 value goes through the end of the string
int count = 0;
// Check each substring length 2 starting at i
for (int i=0; i<str.length()-2; i++) {
String sub = str.substring(i, i+2);
if (sub.equals(end)) { // Use .equals() with strings
count++;
}
}
return count;
}
}