是否存在类似于Python的Easy String Splicing的Java?

ror*_*ory 26 python java string

好吧,我想知道的是有一种方法可以用Java来做Python下面可以做的事情......

string_sample = "hello world"

string_sample[:-1]
>>> "hello world"

string_sample[-1]
>>> "d"

string_sample[3]
>>> "l"
Run Code Online (Sandbox Code Playgroud)

因为在我看来,Java让你为同样的结果工作(我特别需要每次使用2个数字而缺少-1表示最后一个字符)

String string_sample = "hello world";

string_sample.substring(0,string_sample.length()-1);
>>> "hello world"

string_sample.substringstring_sample.length()];
>>> "d"

string_sample.(3,4);
>>> "l"
Run Code Online (Sandbox Code Playgroud)

我还没有在Java中使用数组/列表,所以我真的希望Java比这更容易

编辑:修改了'i'对于string_sample [3]的'l'.好好发现Maroun!

aba*_*ert 19

对不起,Java substring不像Python的切片表示法那么灵活.

特别是:

  • 你可以给它一个开头,或者开始和结束,但不仅仅是结束.(也是,没有一步,但你不要错过那么多.)
  • 负指数是一个错误,而不是从最后的计数.

你可以在这里看到文档.

但是,要自己写这个并不难:

public String slice_start(String s, int startIndex) {
    if (startIndex < 0) startIndex = s.length() + startIndex;
    return s.substring(startIndex);
}

public String slice_end(String s, int endIndex) {
    if (endIndex < 0) endIndex = s.length() + endIndex;
    return s.substring(0, endIndex);
}

public String slice_range(String s, int startIndex, int endIndex) {
    if (startIndex < 0) startIndex = s.length() + startIndex;
    if (endIndex < 0) endIndex = s.length() + endIndex;
    return s.substring(startIndex, endIndex);
}
Run Code Online (Sandbox Code Playgroud)

把它们作为某些实用程序类的静态方法.

显然这与Python不完全相同,但它可能会处理您想要的所有情况,而且非常简单.如果你想处理其他边缘情况(包括步骤和传递切片等等),你可以添加你想要的任何其他代码; 没有一个特别棘手.


其他序列基本相同,但你需要subSequence而不是substring.(你也可以subSequence在字符串上使用,因为a String是a CharSequence.)

数组实际上根本不是一种序列; 您需要编写显式创建新数组并复制子数组的代码.但它仍然没有那么复杂.


请注意,您可能希望查找已经为您完成此操作的库.此页面上的其他答案中至少有三个链接,这将使您的搜索更容易.:)(你可能仍然想为自己做一次,只是为了理解这些库是如何工作的 - 但对于生产代码,我宁愿使用一个其他人已经想出并测试所有边缘情况而不是重新实现的库当他们陷入单元测试或现场错误时,他们会处理这些问题......


Ric*_*igh 10

Java Boon Slice Notation允许所有这些以及字符串,列表,集合,地图等.

许多语言都有切片表示法(Ruby,Groovy和Python).Boon将此添加到Java.

Boon有三个slc运算符:slc,slc(仅限启动)和slcEnd.

使用Boon,您可以切割字符串,数组(原始和通用),列表,集合,树集,树映射等.

切片符号 - 温和的介绍

boon切片操作符的工作方式类似于Python/Ruby切片表示法:

Ruby切片表示法

 arr = [1, 2, 3, 4, 5, 6]
 arr[2]    #=> 3
 arr[-3]   #=> 4
 arr[2, 3] #=> [3, 4, 5]
 arr[1..4] #=> [2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

Python切片表示法

string = "foo bar" 
string [0:3]  #'foo'
string [-3:7] #'bar'
Run Code Online (Sandbox Code Playgroud)

以下内容源自Python的切片表示法的优秀写法:

切片表示法的基础知识如下:

Python切片表示法

     a[ index ]       # index of item
     a[ start : end ] # items start through end-1
     a[ start : ]     # items start through the rest of the array
     a[ : end ]       # items from the beginning through end-1
     a[ : ]           # a copy of the whole array
Run Code Online (Sandbox Code Playgroud)

使用Boon的Java Slice表示法:

      idx( index )         // index of item
      slc( a, start, end ) // items start through end-1
      slc( a, start )      // items start through the rest of the array
      slcEnd( a, end )     // items from the beginning through end-1
      copy( a )            // a copy of the whole array
Run Code Online (Sandbox Code Playgroud)

slc代表切片 idx代表索引 slcEnd代表结束切片. 副本代表好,错误,当然是副本

要记住的关键点是结束值表示不在所选切片中的第一个值.因此,end和start之间的差异是所选元素的数量.另一个特性是开始或结束可能是负数,这意味着它从数组的末尾而不是从开头开始计数.

从而:

带有负索引的Python切片表示法

         a[ -1 ]    # last item in the array
         a[ -2: ]   # last two items in the array
         a[ :-2 ]   # everything except the last two items
Run Code Online (Sandbox Code Playgroud)

Java负面索引

         idx   ( a, -1)     // last item in the array
         slc   ( -2 )       // last two items in the array
         slcEnd( -2 )       // everything except the last two items
Run Code Online (Sandbox Code Playgroud)

Python和Boon对程序员很友好,如果项目少于你要求的项目:Python不允许你超出界限,如果你这样做,则返回更糟糕的空列表.Boon遵循这一传统,但提供了一个获得越界异常的选项(稍后描述).在Python和Boon中,如果你走远,你得到的长度,如果你试图低于0你得到0(计算后低于0).相反,Ruby会给你一个空指针(Nil).Boon复制Python风格,因为Boon的目标之一是避免返回null(你得到一个例外,Option).(Boon有第二个名为zlc的运算符抛出一个越界索引异常,但大多数人应该使用slc.)

例如,如果您要求slcEnd(a,-2)(a [: - 2])并且只包含一个元素,则会得到一个空列表而不是错误.有时您会更喜欢错误,而Boon则有这个选择.

更多切片

以下是一些基本的Java类型,列表,数组,素食,原始字符数组和原始字节数组.

声明要在Boon中使用的变量

//Boon works with lists, arrays, sets, maps, sorted maps, etc.
List<String> fruitList;
String [] fruitArray;
Set<String> veggiesSet;
char [] letters;
byte [] bytes;
NavigableMap <Integer, String> favoritesMap;
Map<String, Integer> map;

//In Java a TreeMap is a SortedMap and a NavigableMap by the way.
Run Code Online (Sandbox Code Playgroud)

Boon带有帮助方法,允许您轻松创建列表,集合,映射,并发映射,有序映射,有序集等.帮助方法是safeList,list,set,sortedSet,safeSet,safeSortedSet等.这个想法是让Java感觉更像列表,而地图则以类型构建.

初始化set,list,字符串数组,字符数组和字节数组

veggiesSet  =  set( "salad", "broccoli", "spinach");
fruitList   =  list( "apple", "oranges", "pineapple");
fruitArray  =  array( "apple", "oranges", "pineapple");
letters     =  array( 'a', 'b', 'c');
bytes       =  array( new byte[]{0x1, 0x2, 0x3, 0x4});
Run Code Online (Sandbox Code Playgroud)

甚至还有创建地图和有序地图的方法,称为map,sortedMap,safeMap(并发)和sortedSafeMap(并发).这些主要是因为Java没有列表,地图等的文字而创建的.

Java:使用map运算符生成SortedMap和Map

 favoritesMap = sortedMap(
      2, "pineapple",
      1, "oranges",
      3, "apple"
 );


 map =    map (
    "pineapple",  2,
    "oranges",    1,
    "apple",      3
 );
Run Code Online (Sandbox Code Playgroud)

您可以使用idx运算符索引映射,列表,数组等.

Java:使用Boon Java idx运算符获取索引处的值

 //Using idx to access a value.

 assert idx( veggiesSet, "b").equals("broccoli");

 assert idx( fruitList, 1 ).equals("oranges");

 assert idx( fruitArray, 1 ).equals("oranges");

 assert idx( letters, 1 ) == 'b';

 assert idx( bytes, 1 )      == 0x2;

 assert idx( favoritesMap, 2 ).equals("pineapple");

 assert idx( map, "pineapple" )  == 2;
Run Code Online (Sandbox Code Playgroud)

idx运算符也适用于负索引.

Java:使用带负值的idx运算符

         //Negative indexes

          assert idx( fruitList, -2 ).equals("oranges");

          assert idx( fruitArray, -2 ).equals("oranges");

          assert idx( letters, -2 ) == 'b';

          assert idx( bytes, -3 )   == 0x2;
Run Code Online (Sandbox Code Playgroud)

Ruby,Groovy和Python都有这个功能.现在你也可以在Java中使用它!Java版本(Boon)与原始数组一起使用,因此您不会自动装箱.

Ruby和Python没有的东西是SortedSets和SortedMaps的切片表示法.您可以使用切片表示法在Java中搜索已排序的地图和已排序的集合

切片表示法适用于有序映射和有序集.

这是一个将几个概念放在一起的例子.

          set = sortedSet("apple", "kiwi", "oranges", "pears", "pineapple")

          slcEnd( set, "o" )      //returns ("oranges", "pears", "pineapple")
          slc( set, "ap", "o" )   //returns ("apple", "kiwi"),
          slc( set, "o" )         //returns ("apple", "kiwi")
Run Code Online (Sandbox Code Playgroud)

您实际上是在对有序映射进行切片,而有序集是在各种查询之间进行的."pi"后面有什么项目?

          after(set, "pi") //pineapple
Run Code Online (Sandbox Code Playgroud)

还有菠萝之前?

          before(set, "pi")
Run Code Online (Sandbox Code Playgroud)

好的,让我们一步一步来......

  NavigableSet<String> set =
          sortedSet("apple", "kiwi", "oranges", "pears", "pineapple");

  assertEquals(

          "oranges", idx(set, "ora")

  );
Run Code Online (Sandbox Code Playgroud)

请记住:TreeSet实现了NavigableSet和SortedSet.

这来自我的博客......

http://rick-hightower.blogspot.com/2013/10/java-slice-notation-to-split-up-strings.html

有更多的例子.

我从Python切片的讨论中得到了一些措辞.

解释Python的切片表示法

这是Boon项目链接:

https://github.com/RichardHightower/boon

现在让我们继续SLICE!

我们可以使用以下方式查找以"o"开头的集合中的第一个水果:

idx(set, "o")
Run Code Online (Sandbox Code Playgroud)

这是我们之前创建的一组水果(set是一个带有"apple","kiwi","oranges","pears","pineapple"的TreeSet).

      assertEquals(

          "oranges", idx(set, "o")

      );
Run Code Online (Sandbox Code Playgroud)

我们发现了橘子!

这里又是,但这次我们正在寻找以"p"开头的水果,即idx(set,"p").

      assertEquals(
          "pears",
          idx(set, "p")
      );
Run Code Online (Sandbox Code Playgroud)

是啊!我们找到了梨!

那些以"pi"开头的水果怎么样,比如"菠萝" - idx(set,"pi")

  assertEquals(
          "pineapple",
          idx(set, "pi")
  );
Run Code Online (Sandbox Code Playgroud)

您也可以要求在另一个项目之后的项目.什么是"pi"之后?之后(设置,"pi")

  assertEquals(

          "pineapple",
          after(set, "pi")

  );
Run Code Online (Sandbox Code Playgroud)

"菠萝"在项目"pi"之后.之后和idx是一样的.那我为什么要添加一个?所以我以前可以有!!! :)如果你想知道"pi"之前的内容怎么办?

之前(设置,"pi")

  assertEquals(

          "pears",
          before(set, "pi")

  );
Run Code Online (Sandbox Code Playgroud)

"ap"和"o"之间的所有水果怎么样?正如我所承诺的那样有切片符号!

slc(设置,"ap","o")

  assertEquals(

          sortedSet("apple", "kiwi"),
          slc(set, "ap", "o")

  );
Run Code Online (Sandbox Code Playgroud)

"o"之后的所有水果怎么样?

slc(设置,"o")

  assertEquals(

          sortedSet("apple", "kiwi"),
          slc(set, "o")

  );
Run Code Online (Sandbox Code Playgroud)

因此"o"之后的所有水果都是"苹果"和"奇异果".

所有水果到"o"怎么样?(slcEnd读到它,因为我正在切片结束.)

slcEnd(设置,"o")

  assertEquals(

          sortedSet("oranges", "pears", "pineapple"),
          slcEnd(set, "o")
  );
Run Code Online (Sandbox Code Playgroud)

因此,包括"o"在内的所有水果都是"橘子","梨子"和"菠萝".

像列表一样安全切片

如果索引超出范围,这些运算符会抛出异常:

使用Boon的Java Slice表示如下:

      ix( index )         // index of item
      zlc( a, start, end ) // items start through end-1
      zlc( a, start )      // items start through the rest of the array
      zlcEnd( a, end )     // items from the beginning through end-1
Run Code Online (Sandbox Code Playgroud)

zlc代表零容差切片 ix代表零容差指数 zlcEnd代表零容差端切片. 副本代表好,错误,当然是副本

男孩和女孩......记得总是用你不认识的物品进行安全切片.

也适用于基元,所以没有自动装箱

索引基元

 byte[] letters =
      array((byte)'a', (byte)'b', (byte)'c', (byte)'d');

 assertEquals(
      'a',
      idx(letters, 0)
 );


 assertEquals(
      'd',
      idx(letters, -1)
 );


 assertEquals(
      'd',
      idx(letters, letters.length - 1)
 );

 idx(letters, 1, (byte)'z');

 assertEquals(
      (byte)'z',
      idx(letters, 1)
 );
Run Code Online (Sandbox Code Playgroud)

方法len和idx是通用运算符,它们可用于列表,数组,集合,映射等.

len给我一个类似数组,类似列表,类似地图的东西的长度. idx在类似数组,类似列表的地图中的"索引"位置给我项目.

HOME MC String Slice!

以下是Boon Java String Slicing的一些示例

  String letters = "abcd";

  boolean worked = true;

  worked &=

          idx(letters, 0)  == 'a'
                  || die("0 index is equal to a");



  worked &=

          idx(letters, -1)  == 'd'
                  || die("-1 index is equal to a");
Run Code Online (Sandbox Code Playgroud)

另一种表达idx(字母,-1)=='d'的方法是idx(letters,letters.length() - 1)=='d'!我更喜欢更短的方式!

  worked &=

          idx(letters, letters.length() - 1) == 'd'
                   || die("another way to express what the -1 means");


  //We can modify too
  letters = idx(letters, 1, 'z');

  worked &=

          idx(letters, 1) == 'z'
                  || die("Set the 1 index of letters to 'z'");


  worked &= (
          in('a', letters) &&
          in('z', letters)
  ) || die("'z' is in letters and 'a' is in letters");
Run Code Online (Sandbox Code Playgroud)

切片宝贝!

  letters = "abcd";

  worked &=
          slc(letters, 0, 2).equals("ab")
              || die("index 0 through index 2 is equal to 'ab'");



  worked &=
          slc(letters, 1, -1).equals("bc")
                  || die("index 1 through index (length -1) is equal to 'bc'");


  worked &=
          slcEnd(letters, -2).equals("ab")
                  || die("Slice of the end of the string!");


  worked &=
          slcEnd(letters, 2).equals("ab")
                  || die("Vanilla Slice Slice baby!");
Run Code Online (Sandbox Code Playgroud)

在我的5.0滚动,我的抹布上下,所以我的头发可以吹!切片宝贝!!!


mil*_*ose 7

Apache commons-lang在StringUtils中对此有一些支持:

从指定的String中获取子字符串,避免异常.

负起始位置可用于从String的末尾开始n个字符

但是你仍然必须使用显式的起始索引.