如何在java中仅使用substring()方法实现trim()方法



我知道这个问题很愚蠢,但在一次采访中,我被告知要实现trim()方法,除了substring()方法之外,不使用String类中的任何方法。

我通过使用 toCharArray() 然后识别 String 的第一个和最后一个有效字符来解决这个问题。但被告知不要使用toCharArray()方法。

谁能提出一些方法来做到这一点。

允许使用 Objects 类的重写方法,如 equals() 和 hashCode()。

String untrimmed = "  some   string   ";
String trimmed = "";
String innerSpaces = "";
boolean wordBoundary = true;
try {
    for (int i = 0; ; i++) {
        String substr = untrimmed.substring(i, i + 1);
        if (!substr.equals(" ") && !substr.equals("t") && 
               !substr.equals("n") && !substr.equals("r")) {
            trimmed += innerSpaces + substr;
            wordBoundary = false;
            innerSpaces = "";
        }
        else if (!wordBoundary) {
            innerSpaces += substr;
        }
    }
}
catch (IndexOutOfBoundsException e)  { }
System.out.println(trimmed);
当然,

修剪后的结果需要substring

如果没有任何String方法,就很难在两端找到可能的空间。

仍然:

  1. 外部处理:

    某种形式的

    Pattern pattern = Pattern.compile("\s*(\S*)\s*"); // Pattern not okay
    Matcher m = pattern.matcher(string);
    string = m.matches()? m.group(1) : string;
    

    或:

    Set<String> set0 = new HashSet<>();
    set0.add(string);
    Set<String> set = new HashSet<>();
    try {
        set.add(" " + string.substring(1));
        if (set0.contains(set)) {
            ...
    } catch (IndexOutOfRangeException e) { ... }
    
  2. 使用字符串的超类的方法。但是,没有一个不被字符串本身覆盖。也许允许以下情况:

    CharSequence cs = string;
    // Use cs.charAt or Whatever
    

两者都似乎是法律主义的解决方案。我很想知道他们的解决方案——或者这是一个不可能回答的问题。

Hacky,但这个问题无论如何都是愚蠢的:

public static String trim(String s) {
    StringBuilder sb = new StringBuilder(s);
    int start, end;
    for (start = 0; start < sb.length() && Character.isWhitespace(sb.charAt(start)); start++);
    for (end = sb.length() - 1; end > start && Character.isWhitespace(sb.charAt(end)); end--);
    return sb.substring(start, end + 1);
}
System.out.println(trim("   n t trim me  t "));

你可以作弊,而是间接调用String的方法:

StringBuilder sb = new StringBuilder(sb);
for (int i = 0; i < sb.length(); i++) {
   char ch = sb.charAt(i);
   ...
}

如果有人问,你没有在String上调用任何方法,甚至没有substring()StringBuilder为您做到这一点。:)

总而言之,这是一个可怕的问题,我不会担心。

一个非常低效的解决方案,但它就在这里。

您在评论中说您可以使用 .equals() 方法。因此,这是我精心设计的解决方案:

你知道汽车里的那些里程计数器吗?那些去 0000、0001、0002...等。?用字符数组列表来模拟它。

从大小 1 开始,遍历每个字符,使用mainString.equals(charArrayList.toString())进行比较。如果您通关了所有字符,并且不匹配,请将大小增加一个并重复。匹配后,您可以在开头和结尾检查空格字符。

请记住,我知道这效率不高,但它有效。即使需要一年:)

希望这有帮助!

如果您首先根据substring重新定义length()charAt(),这并不难......当然,它效率低下(长度现在需要O(n^2)),但它可以完成工作,并且作为奖励定义了length()charAt()

  public static int length(String s) {
    for(int i = 0; i < Integer.MAX_VALUE; i++) {
      try {
        s.substring(i);
      }catch(StringIndexOutOfBoundsException e) {
        return i - 1;
      }
    }
    return Integer.MAX_VALUE;
  }
  public static char charAt(String s, int idx) {
    String c = s.substring(idx, idx+1);
    return (char)c.hashCode();
  }
  public static String trim(String s) {
    final int length = length(s);
    int startIndex;
    int endIndex;
    for(startIndex = 0; startIndex < length; startIndex++) {
      char c = charAt(s, startIndex);
      if(! Character.isWhitespace(c)) {
        break;
      }
    }
    for(endIndex = length; endIndex > startIndex; endIndex--) {
      char c = charAt(s, endIndex - 1);
      if(! Character.isWhitespace(c)) {
        break;
      }
    }
    return s.substring(startIndex, endIndex);
  }

相关内容

最新更新