mixin дает возможность добавить функциональность в класс, т. е. вы можете взаимодействовать с методами, определенными в модуле, включая модуль внутри желаемого класса. Хотя ruby не поддерживает множественное наследование, но предоставляет mixin в качестве альтернативы для достижения этого.
вот пример, который объясняет, как достигается множественное наследование с помощью mixin.
module A # you create a module
def a1 # lets have a method 'a1' in it
end
def a2 # Another method 'a2'
end
end
module B # let's say we have another module
def b1 # A method 'b1'
end
def b2 #another method b2
end
end
class Sample # we create a class 'Sample'
include A # including module 'A' in the class 'Sample' (mixin)
include B # including module B as well
def S1 #class 'Sample' contains a method 's1'
end
end
samp = Sample.new # creating an instance object 'samp'
# we can access methods from module A and B in our class(power of mixin)
samp.a1 # accessing method 'a1' from module A
samp.a2 # accessing method 'a2' from module A
samp.b1 # accessing method 'b1' from module B
samp.b2 # accessing method 'a2' from module B
samp.s1 # accessing method 's1' inside the class Sample
Вы можете сделать это так:
String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));
, что дает:
[123, 456, 789, 0]
Регулярное выражение (? <= \ G ...)
соответствует пустой строке с последним совпадением ( \ G
), за которым следуют три символа ( ...
) перед it ( (? <=)
)
Я недавно встретился с этой проблемой и здесь являюсь решением, которое я предложил
final int LENGTH = 10;
String test = "Here is a very long description, it is going to be past 10";
Map<Integer,StringBuilder> stringBuilderMap = new HashMap<>();
for ( int i = 0; i < test.length(); i++ ) {
int position = i / LENGTH; // i<10 then 0, 10<=i<19 then 1, 20<=i<30 then 2, etc.
StringBuilder currentSb = stringBuilderMap.computeIfAbsent( position, pos -> new StringBuilder() ); // find sb, or create one if not present
currentSb.append( test.charAt( i ) ); // add the current char to our sb
}
List<String> comments = stringBuilderMap.entrySet().stream()
.sorted( Comparator.comparing( Map.Entry::getKey ) )
.map( entrySet -> entrySet.getValue().toString() )
.collect( Collectors.toList() );
//done
// here you can see the data
comments.forEach( cmt -> System.out.println( String.format( "'%s' ... length= %d", cmt, cmt.length() ) ) );
// PRINTS:
// 'Here is a ' ... length= 10
// 'very long ' ... length= 10
// 'descriptio' ... length= 10
// 'n, it is g' ... length= 10
// 'oing to be' ... length= 10
// ' past 10' ... length= 8
// make sure they are equal
String joinedString = String.join( "", comments );
System.out.println( "\nOriginal strings are equal " + joinedString.equals( test ) );
// PRINTS: Original strings are equal true
Java не предоставляет полнофункциональных утилит разделения, поэтому библиотеки Guava делают:
Iterable<String> pieces = Splitter.fixedLength(3).split(string);
Проверьте Документация Javadoc для Splitter ; это очень мощно.
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
for (String part : getParts("foobarspam", 3)) {
System.out.println(part);
}
}
private static List<String> getParts(String string, int partitionSize) {
List<String> parts = new ArrayList<String>();
int len = string.length();
for (int i=0; i<len; i+=partitionSize)
{
parts.add(string.substring(i, Math.min(len, i + partitionSize)));
}
return parts;
}
}