有人可以在java中解释这段代码的答案吗?

时间:2016-01-09 03:24:45

标签: java string

这是问题

  

给定一个字符串,返回一个已删除所有“x”的版本。   除了开头或结尾处的“x”外,不应删除。

     
      
  • stringX("xxHxix")"xHix"
  •   
  • stringX("abxxxcd")"abcd"
  •   
  • stringX("xabxxxcdx")"xabcdx"
  •   

现在我理解了这个问题,但解决方案对我来说还不清楚,有人可以解释一下吗?

答案=

public String stringX(String str) {
  String result = "";
  for (int i=0; i<str.length(); i++) {
    // Only append the char if it is not the "x" case
    if (!(i > 0 && i < (str.length()-1) && str.substring(i, i+1).equals("x"))) {
      result = result + str.substring(i, i+1); // Could use str.charAt(i) here
    }
  }
  return result;
}

我的解决方案也是有效的,这一个=

public String stringX(String str) {

  String ans = "";

  if(str.length() == 0) return ans;
  if(str.charAt(0) == 'x') ans += "x";

  for(int i = 0; i < str.length(); i++)
  {
    if(str.charAt(i) == 'x') continue;
    ans += (char) str.charAt(i);
  }

  if(str.charAt(str.length()-1) == 'x' && str.length() > 1) ans += "x";

  return ans;
}

1 个答案:

答案 0 :(得分:4)

public String stringX(String str) {

  // Create an empty string to hold the input without 'x's
  String result = "";

  // Loop for as many characters there are in the string
  for (int i=0; i<str.length(); i++) {

    // If the current character we're looking at isn't the first OR last character
    // and we check to see if that character equals 'x', then we take the opposite
    // of this entire value.
    // Another way to read this logic is:
    // If the character we're looking at is the first OR the last OR it doesn't equal 'x',
    // then continue (return true)
    if (!(i > 0 && i < (str.length()-1) && str.substring(i, i+1).equals("x"))) {

      // We add this character to our output string
      result = result + str.substring(i, i+1); // Could use str.charAt(i) here
    }
  }

  // Return our output string
  return result;
}