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

Can someone explain me the answer of this code in java?

这就是问题所在

Given a string, return a version where all the "x" have been removed. Except an "x" at the very start or end should not be removed.

  • 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;
}
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;
}