如何使用substring()方法在java中实现trim()方法(How to implement trim() method in java by using only substring() m

编程入门 行业动态 更新时间:2024-10-27 19:19:49
如何使用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);

更多推荐

本文发布于:2023-08-06 19:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1455379.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   如何使用   substring   java   implement

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!