从右手方向在 JAVA 中使用子字符串

是否可以substring()在 JAVA 中使用右手(反向)方向获取子字符串。例子。假设String S="abcdef",我可以使用子串“fedc”S.substring(S.length()-1,3)吗?如果不正确,请建议我如何从右手端(反向)获取子字符串??


红糖糍粑
浏览 171回答 3
3回答

杨__羊羊

您可以反转字符串并使用substring. 不幸的String是没有那个,但StringBuilder有它,例如new StringBuilder("abcdef").reverse().toString().substring(0,4);

慕慕森

Java 不支持像 C# 那样的扩展方法,所以我会为此构建一个函数。通过这种方式,您可以使用参数控制所需的反向子字符串的数量。public class StackOverflow {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String data = "abcdef";&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < data.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(reverseSubstring(data, i+1));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; public static String reverseSubstring(String data, int length) {&nbsp; &nbsp; &nbsp; &nbsp; return new StringBuilder(data).reverse().substring(0, length);&nbsp; &nbsp; }}结果:ffefedfedcfedcbfedcba更新另一种方法是为 String 创建一个包装类。通过这种方式,您可以调用类方法,就像您在示例中提出的问题一样S.substring(S.length()-1,3)。这也将允许您String在使用包装器的get()方法后仍然拥有所有方法。字符串包装器public class MyString {&nbsp; &nbsp; private String theString;&nbsp; &nbsp; public MyString(String s) {&nbsp; &nbsp; &nbsp; &nbsp; theString = s;&nbsp; &nbsp; }&nbsp; &nbsp; public String get() {&nbsp; &nbsp; &nbsp; &nbsp; return theString;&nbsp; &nbsp; }&nbsp; &nbsp; public String reverseSubstring(int length) {&nbsp; &nbsp; &nbsp; &nbsp; return new StringBuilder(theString).reverse().substring(0, length);&nbsp; &nbsp; }}用法public class StackOverflow {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; MyString data = new MyString("abcdef");&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < data.get().length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(data.reverseSubstring(i+1));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp;}结果:ffefedfedcfedcbfedcba

千万里不及你

您可以反转字符串并找到子字符串// reverseString s = "abcdef";StringBuilder builder = new StringBuilder(s);String substring = builder.reverse().substring(0,3);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java