如何使用substring()方法在java中实现trim()方法(How to implement trim() method in java by using only substring() method)
我知道这个问题很愚蠢,但在一次采访中,我被告知实现trim()方法时不使用任何方法从String类除了substring()方法。
我通过使用toCharArray()来处理这个问题,然后确定String的第一个和最后一个有效字符。 但被告知不要使用toCharArray()方法。
任何人都可以提出一些方法来实现它。
Object类的Overriden方法与equals()和hashCode()类似。
I know this question is quite silly, but in an interview I was told to implement trim() method without using any method from String class except substring() method.
I approached this problem by using toCharArray() and then identifying the first and last valid character of String. But was told not to use toCharArray() method.
Could anyone suggest some approach to do it.
Overriden methods of Objects class are allowed like equals() and 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); 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);更多推荐
发布评论