I tried to search online to solve this question but I didn't found anything.
I wrote the following abstract code to explain what I'm asking:
String text = "how are you?";
String[] textArray= text.splitByNumber(4); //this method is what I'm asking
textArray[0]; //it contains "how "
textArray[1]; //it contains "are "
textArray[2]; //it contains "you?"
The method splitByNumber splits the string "text" every 4 characters. How I can create this method??
Many Thanks
I think that what he wants is to have a string split into substrings of size 4. Then I would do this in a loop:
List<String> strings = new ArrayList<String>();
int index = 0;
while (index < text.length()) {
strings.add(text.substring(index, Math.min(index + 4,text.length())));
index += 4;
}
Using Guava:
Iterable<String> result = Splitter.fixedLength(4).split("how are you?");
String[] parts = Iterables.toArray(result, String.class);
What about a regexp?
public static String[] splitByNumber(String str, int size) {
return (size<1 || str==null) ? null : str.split("(?<=\\G.{"+size+"})");
}
See Split string to equal length substrings in Java
Try this
String text = "how are you?";
String array[] = text.split(" ");
Or you can use it below
List<String> list= new ArrayList<String>();
int index = 0;
while (index<text.length()) {
list.add(text.substring(index, Math.min(index+4,text.length()));
index=index+4;
}
Quick Hack
private String[] splitByNumber(String s, int size) {
if(s == null || size <= 0)
return null;
int chunks = s.length() / size + ((s.length() % size > 0) ? 1 : 0);
String[] arr = new String[chunks];
for(int i = 0, j = 0, l = s.length(); i < l; i += size, j++)
arr[j] = s.substring(i, Math.min(l, i + size));
return arr;
}
Using simple java primitives and loops.
private static String[] splitByNumber(String text, int number) {
int inLength = text.length();
int arLength = inLength / number;
int left=inLength%number;
if(left>0){++arLength;}
String ar[] = new String[arLength];
String tempText=text;
for (int x = 0; x < arLength; ++x) {
if(tempText.length()>number){
ar[x]=tempText.substring(0, number);
tempText=tempText.substring(number);
}else{
ar[x]=tempText;
}
}
return ar;
}
Usage : String ar[]=splitByNumber("nalaka", 2);
I don't think there's an out-of-the-box solution, but I'd do something like this:
private String[] splitByNumber(String s, int chunkSize){
int chunkCount = (s.length() / chunkSize) + (s.length() % chunkSize == 0 ? 0 : 1);
String[] returnVal = new String[chunkCount];
for(int i=0;i<chunkCount;i++){
returnVal[i] = s.substring(i*chunkSize, Math.min((i+1)*chunkSize-1, s.length());
}
return returnVal;
}
Usage would be:
String[] textArray = splitByNumber(text, 4);
EDIT: the substring actually shouldn't surpass the string length.
This is the simplest solution i could think off.. try this
public static String[] splitString(String str) {
if(str == null) return null;
List<String> list = new ArrayList<String>();
for(int i=0;i < str.length();i=i+4){
int endindex = Math.min(i+4,str.length());
list.add(str.substring(i, endindex));
}
return list.toArray(new String[list.size()]);
}
Here's a succinct implementation using Java8 streams:
String text = "how are you?";
final AtomicInteger counter = new AtomicInteger(0);
Collection<String> strings = text.chars()
.mapToObj(i -> String.valueOf((char)i) )
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 4
,Collectors.joining()))
.values();
Output:
[how , are , you?]
Try this solution,
public static String[]chunkStringByLength(String inputString, int numOfChar) {
if (inputString == null || numOfChar <= 0)
return null;
else if (inputString.length() == numOfChar)
return new String[]{
inputString
};
int chunkLen = (int)Math.ceil(inputString.length() / numOfChar);
String[]chunks = new String[chunkLen + 1];
for (int i = 0; i <= chunkLen; i++) {
int endLen = numOfChar;
if (i == chunkLen) {
endLen = inputString.length() % numOfChar;
}
chunks[i] = new String(inputString.getBytes(), i * numOfChar, endLen);
}
return chunks;
}
My application uses text to speech!
Here is my algorithm, to split by "dot" and conconate string if string length less then limit
String[] text = sentence.split("\\.");
ArrayList<String> realText = sentenceSplitterWithCount(text);
Function sentenceSplitterWithCount: (I concanate string lf less than 100 chars lenght, It depends on you)
private ArrayList<String> sentenceSplitterWithCount(String[] splittedWithDot){
ArrayList<String> newArticleArray = new ArrayList<>();
String item = "";
for(String sentence : splittedWithDot){
item += DataManager.setFirstCharCapitalize(sentence)+".";
if(item.length() > 100){
newArticleArray.add(item);
item = "";
}
}
for (String a : newArticleArray){
Log.d("tts", a);
}
return newArticleArray;
}
function setFirstCharCapitalize just capitalize First letter: I think, you dont need it, anyway
public static String setFirstCharCapitalize(String input) {
if(input.length()>2) {
String k = checkStringStartWithSpace(input);
input = k.substring(0, 1).toUpperCase() + k.substring(1).toLowerCase();
}
return input;
}
Related
So I'm trying to write an algorithm that counts the number of occurrences of some pattern, say "aa", within a string, say "aaabca." The number of patterns in that string should return an integer, in this case 2, because the first three characters contain two occurrences of the pattern.
What I have finds the number of patterns under the assumption the existing occurrences of a pattern is NOT overlapping:
public class Pattern{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string: ");
String s = scan.nextLine();
String[] splittedInput = s.split(";");
String pattern = splittedInput[0];
String blobs = splittedInput[1];
Pattern p = new Pattern();
p.count(pattern, blobs);
}
public static void count(String pattern, String blobs){
String[] substrings = blobs.split("[|]");
int numOccurences = 0;
int[] instances = new int[substrings.length];
int patternLength = pattern.length();
for (int i = 0; i < instances.length; i++){
int length = substrings[i].length();
String temp = substrings[i];
temp = temp.replaceAll(pattern, "");
int postLength = temp.length();
numOccurences = (length - postLength) / pattern.length();
instances[i] = numOccurences;
numOccurences = 0;
}
int sum = 0;
for (int i = 0; i < instances.length; i++){
System.out.print(instances[i] + "|");
sum += instances[i];
}
System.out.print(sum);
}
}
Any suggestions?
I would personally compare the pattern as a substring in this case. For example a run of a single String from your array would look like this:
//Initial values
String blobs = "aaaabcaaa";
String pattern = "aab";
String[] substrings = blobs.split("[|]");
//The code I added that should placed into the loop
int numOccurences = 0;
String str = substrings[0];
for (int k = 0; k <= (str.length() - pattern.length()); k++)
{
if (str.substring(k, k + pattern.length()).equals(pattern))
{
numOccurences++;
}
}
System.out.println(numOccurences);
If you want to run this on each String in your array simply modify String str = substrings[0] to String str = substrings[i] and iterate over the array storing the final numOccurences as you please.
Example Run:
String is aaaabcaaa
Pattern is aa
Output is 5 occurences
For one String, match is the String you're looking for:
int len = theStr.length ();
int start = 0;
int pos;
int count = 0;
while ((start < len) && ((pos = theStr.indexOf (match, start)) >= 0))
{
++count;
start = pos + 1;
}
If you use Java 8 you can count this value in the following way.
Example:
String blobs = "aaabcaaa";
String pattern = "aa";
List<String> strings = Arrays.asList(blobs.split(""));
long count = IntStream.range(0, strings.size())
.mapToObj(index -> index < strings.size() - 1 ? strings.get(index) + strings.get(index + 1) : strings.get(index - 1))
.filter(str -> str.equals(pattern))
.count();
System.out.println("Result count: " + count);
Continually taking substrings and using the startsWith method seems to work pretty well.
String pat = "ss";
String str = "kskslsksaaaslsslssskssssllsssss";
int count = 0;
while (str.length() >= pat.length()) {
count += str.startsWith(pat) ? 1 : 0;
str = str.substring(1);
}
System.out.println("count = " + count);
You can also take a similar approach with streams.
long count = IntStream.range(0, str.length()).mapToObj(
n -> str.substring(n)).filter(n -> n.startsWith(pat)).count();
System.out.println("count = " + count);
But in this case I actually prefer the non-stream approach.
I would like to re-format a String array based on condition. Say, the array
A = ["samsung", "chargers", "fast", "charging", "rapid", "high"]
int index = 1
Which means I will adjoin the items till index 1 with space and format the array. So, finally, it will be,
A = ["samsung chargers", "fast", "charging", "rapid", "high"]
For the index = 2, the output should be,
A = ["samsung chargers fast", "charging", "rapid", "high"]
I write the code that works, I try to find more concise (but not low performance) way.
StringBuilder builder = null;
..........
int fCount = ...
// format the array to match the string
// values = ["samsung", "chargers", "fast", "charging", "rapid", "high"]
builder = new StringBuilder();
String formated = "";
for (int i = 0; i <= fCount; i++) {
builder.append(values[i]).append(" ");
}
formated = builder.toString().trim();
String[] fVaues = new String[values.length - fCount];
fVaues[0] = formated;
for (int i = 1; i < fVaues.length; i++) {
fVaues[i] = values[i+1];
}
What is the simple way to accomplish it?
This method does the same thing:
static String[] joinUntil(String[] original, int until) {
return Stream.concat(
Stream.of(String.join(" ", Arrays.copyOf(original, until))),
Arrays.stream(Arrays.copyOfRange(original, until, original.length))
).toArray(String[]::new);
}
private static List<String> reFormat(List<String> lst, int index){
String joined = String.join(" ", lst.subList(0, index + 1));
List<String> res = new ArrayList<String>();
res.add(joined);
res.addAll(lst.subList(index + 1, lst.size()));
return res;
}
You could just loop over it, adding the Strings to a second array:
String[] b = new String[a.length - index];
String tmp = a[0];
for(int i = 1; i < a.length; i++) {
if(i <= index) {
tmp += " " + a[i];
if(i == index) {
b[i - index] = tmp;
}
}
else {
b[i - index] = a[i];
}
}
I was working on a Java coding problem and encountered the following issue.
Input: A String -> "Code"
Output Expected: A string -> CCoCodCode
My Code snippet: (Note: In comments I have written what I expect upon passing the string)
public String stringSplosion(String str) { // string Say 'Code'
String join = "", values = "";
String gotIt = "";
int n = str.length(); // 4
int size = 0;
for (int i = n; i >= 1; i--) {
size = size + n; // 4+3+2+1=10
}
String[] result = new String[size];
for (int i = 0; i < str.length(); i++) {
values = str.substring(i, i + 1);
join = join + values;
result[i] = join;
}
for (String s : result) {
gotIt = gotIt + s;
}
return gotIt; // Expected output: CCoCodCode
}
Output I am getting:
CCoCodCodenullnullnullnullnullnullnullnullnullnullnullnull
Why is null getting stored although I have reduced the size and how can I remove it?
NOTE: I need to solve this using arrays. I know it is much easier using List.
If you want to keep the current structure of your code, get rid of the first for loop.
And create String[] array = new String[n]
public static String stringSplosion(String str) { // string Say 'Code'
String join = "", values = "";
String gotIt = "";
int n = str.length(); // 4
String[] result = new String[n]; //you want your String array to contain 4 strings
for (int i = 0; i < str.length(); i++) {
values = str.substring(i, i + 1);
join = join + values;
result[i] = join;
}
for (String s : result) {
gotIt = gotIt + s;
}
return gotIt; // Expected output: CCoCodCode
}
public class Answer {
public static String answer(String input){
StringBuilder sb = new StringBuilder(((input.length() + 1) * input.length()) / 2);
for (int i = 1; i <= input.length(); i++) {
sb.append(input.substring(0, i));
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(answer("Code"));
}
}
Below statements are not required:
int size = 0;
for (int i = n; i >= 1; i--) {
size = size + n; // 4+3+2+1=10
}
You just need to change the array size from
String[] result = new String[size];
to
String[] result = new String[n];
for your program to give the expected output.
If I understand ur problem correctly to print the pattern then u can use below code,
public String printPattern(String input){
//Holds the iteration value by index
int previous=0;
//It holds the result characters
String result=null;
StringBuilder strBuilder=new StringBuilder();
//first loop to iterate only till input string length
for(int i=0;i<input.length();i++){
//checking iteration lenght with input string length
if(previous<input.length()){
//incrementing iteration for reading characters from input string
previous++;
//main loop for previous iteration value check and iterate
for(int j=0;j<previous;j++){
//converting string to Character array
char a []=input.toCharArray();
//using string builder to build the string from characters
strBuilder.append((a[j]));
//setting the value to stringbuilder by converting it in string
result=strBuilder.toString();
}
}
}
return result;
}
Size should be the length of string. Code's length is 4. Code will produce {C, Co, Cod, Code}.
public String stringSplosion(String str) { // string Say 'Code'
String join = "", values = "";
String gotIt = "";
int n = str.length(); // 4
String[] result = new String[n];
for (int i = 0; i < str.length(); i++) {
values = str.substring(i, i + 1);
join = join + values;
result[i] = join;
}
System.out.println(Arrays.toString(result));
for (String s : result) {
gotIt = gotIt + s;
}
return gotIt; // Expected output: CCoCodCode
}
String input = "Code";
String output[] = IntStream.range(0, input.length()+1)
.mapToObj(i -> input.substring(0, i))
.toArray(String[]::new);
I would like to split a string at every 4th occurrence of a comma ,.
How to do this? Below is an example:
String str = "1,,,,,2,3,,1,,3,,";
Expected output:
array[0]: 1,,,,
array[1]: ,2,3,,
array[2]: 1,,3,,
I tried using Google Guava like this:
Iterable<String> splitdata = Splitter.fixedLength(4).split(str);
output: [1,,,, ,,2,, 3,,1, ,,3,, ,]
I also tried this:
String [] splitdata = str.split("(?<=\\G.{" + 4 + "})");
output: [1,,,, ,,2,, 3,,1, ,,3,, ,]
Yet this is is not the output I want. I just want to split the string at every 4th occurrence of a comma.
Thanks.
Take two int variable. One is to count the no of ','. If ',' occurs then the count will move. And if the count is go to 4 then reset it to 0. The other int value will indicate that from where the string will be cut off. it will start from 0 and after the first string will be detected the the end point (char position in string) will be the first point of the next. Use the this start point and current end point (i+1 because after the occurrence happen the i value will be incremented). Finally add the string in the array list. This is a sample code. Hope this will help you. Sorry for my bad English.
String str = "1,,,,,2,3,,1,,3,,";
int k = 0;
int startPoint = 0;
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ',')
{
k++;
if (k == 4)
{
String ab = str.substring(startPoint, i+1);
System.out.println(ab);
arrayList.add(ab);
startPoint = i+1;
k = 0;
}
}
}
Here's a more flexible function, using an idea from this answer:
static List<String> splitAtNthOccurrence(String input, int n, String delimiter) {
List<String> pieces = new ArrayList<>();
// *? is the reluctant quantifier
String regex = Strings.repeat(".*?" + delimiter, n);
Matcher matcher = Pattern.compile(regex).matcher(input);
int lastEndOfMatch = -1;
while (matcher.find()) {
pieces.add(matcher.group());
lastEndOfMatch = matcher.end();
}
if (lastEndOfMatch != -1) {
pieces.add(input.substring(lastEndOfMatch));
}
return pieces;
}
This is how you call it using your example:
String input = "1,,,,,2,3,,1,,3,,";
List<String> pieces = splitAtNthOccurrence(input, 4, ",");
pieces.forEach(System.out::println);
// Output:
// 1,,,,
// ,2,3,,
// 1,,3,,
I use Strings.repeat from Guava.
try this also, if you want result in array
String str = "1,,,,,2,3,,1,,3,,";
System.out.println(str);
char c[] = str.toCharArray();
int ptnCnt = 0;
for (char d : c) {
if(d==',')
ptnCnt++;
}
String result[] = new String[ptnCnt/4];
int i=-1;
int beginIndex = 0;
int cnt=0,loopcount=0;
for (char ele : c) {
loopcount++;
if(ele==',')
cnt++;
if(cnt==4){
cnt=0;
result[++i]=str.substring(beginIndex,loopcount);
beginIndex=loopcount;
}
}
for (String string : result) {
System.out.println(string);
}
This work pefectly and tested in Java 8
public String[] split(String input,int at){
String[] out = new String[2];
String p = String.format("((?:[^/]*/){%s}[^/]*)/(.*)",at);
Pattern pat = Pattern.compile(p);
Matcher matcher = pat.matcher(input);
if (matcher.matches()) {
out[0] = matcher.group(1);// left
out[1] = matcher.group(2);// right
}
return out;
}
//Ex: D:/folder1/folder2/folder3/file1.txt
//if at = 2, group(1) = D:/folder1/folder2 and group(2) = folder3/file1.txt
The accepted solution above by Saqib Rezwan does not add the leftover string to the list, if it divides the string after every 4th comma and the length of the string is 9 then it will leave the 9th character, and return the wrong list.
A complete solution would be :
private static ArrayList<String> splitStringAtNthOccurrence(String str, int n) {
int k = 0;
int startPoint = 0;
ArrayList<String> list = new ArrayList();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',') {
k++;
if (k == n) {
String ab = str.substring(startPoint, i + 1);
list.add(ab);
startPoint = i + 1;
k = 0;
}
}
// if there is no comma left and there are still some character in the string
// add them to list
else if (!str.substring(i).contains(",")) {
list.add(str.substring(startPoint));
break;
}
}
return list;
}
}
The following code will print 2
String word = "bannanas";
String guess = "n";
int index;
System.out.println(
index = word.indexOf(guess)
);
I would like to know how to get all the indexes of "n" ("guess") in the string "bannanas"
The expected result would be: [2,3,5]
This should print the list of positions without the -1 at the end that Peter Lawrey's solution has had.
int index = word.indexOf(guess);
while (index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index + 1);
}
It can also be done as a for loop:
for (int index = word.indexOf(guess);
index >= 0;
index = word.indexOf(guess, index + 1))
{
System.out.println(index);
}
[Note: if guess can be longer than a single character, then it is possible, by analyzing the guess string, to loop through word faster than the above loops do. The benchmark for such an approach is the Boyer-Moore algorithm. However, the conditions that would favor using such an approach do not seem to be present.]
Try the following (Which does not print -1 at the end now!)
int index = word.indexOf(guess);
while(index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index+1);
}
This can be done in a functional way with Java 9 using regular expression:
Pattern.compile(Pattern.quote(guess)) // sanitize input and create pattern
.matcher(word) // create matcher
.results() // get the MatchResults, Java 9 method
.map(MatchResult::start) // get the first index
.collect(Collectors.toList()) // collect found indices into a list
);
Here's the Kotlin Solution to add this logic as a new a new methods into CharSequence API using extension method:
// Extension method
fun CharSequence.indicesOf(input: String): List<Int> =
Regex(Pattern.quote(input)) // build regex
.findAll(this) // get the matches
.map { it.range.first } // get the index
.toCollection(mutableListOf()) // collect the result as list
// call the methods as
"Banana".indicesOf("a") // [1, 3, 5]
String string = "bannanas";
ArrayList<Integer> list = new ArrayList<Integer>();
char character = 'n';
for(int i = 0; i < string.length(); i++){
if(string.charAt(i) == character){
list.add(i);
}
}
Result would be used like this :
for(Integer i : list){
System.out.println(i);
}
Or as a array :
list.toArray();
With Java9, one can make use of the iterate(int seed, IntPredicate hasNext,IntUnaryOperator next) as follows:-
List<Integer> indexes = IntStream
.iterate(word.indexOf(c), index -> index >= 0, index -> word.indexOf(c, index + 1))
.boxed()
.collect(Collectors.toList());
System.out.printlnt(indexes);
int index = -1;
while((index = text.indexOf("on", index + 1)) >= 0) {
LOG.d("index=" + index);
}
Java 8+
To find all the indexes of a particular character in a String, one can create an IntStream of all the indexes and filter over it.
import java.util.stream.Collectors;
import java.util.stream.IntStream;
//...
String word = "bannanas";
char search = 'n';
//To get List of indexes:
List<Integer> indexes = IntStream.range(0, word.length())
.filter(i -> word.charAt(i) == search).boxed()
.collect(Collectors.toList());
//To get array of indexes:
int[] indexes = IntStream.range(0, word.length())
.filter(i -> word.charAt(i) == search).toArray();
String word = "bannanas";
String guess = "n";
String temp = word;
while(temp.indexOf(guess) != -1) {
int index = temp.indexOf(guess);
System.out.println(index);
temp = temp.substring(index + 1);
}
String input = "GATATATGCG";
String substring = "G";
String temp = input;
String indexOF ="";
int tempIntex=1;
while(temp.indexOf(substring) != -1)
{
int index = temp.indexOf(substring);
indexOF +=(index+tempIntex)+" ";
tempIntex+=(index+1);
temp = temp.substring(index + 1);
}
Log.e("indexOf ","" + indexOF);
Also, if u want to find all indexes of a String in a String.
int index = word.indexOf(guess);
while (index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index + guess.length());
}
I had this problem as well, until I came up with this method.
public static int[] indexesOf(String s, String flag) {
int flagLen = flag.length();
String current = s;
int[] res = new int[s.length()];
int count = 0;
int base = 0;
while(current.contains(flag)) {
int index = current.indexOf(flag);
res[count] = index + base;
base += index + flagLen;
current = current.substring(current.indexOf(flag) + flagLen, current.length());
++ count;
}
return Arrays.copyOf(res, count);
}
This method can be used to find indexes of any flag of any length in a string, for example:
public class Main {
public static void main(String[] args) {
int[] indexes = indexesOf("Hello, yellow jello", "ll");
// Prints [2, 9, 16]
System.out.println(Arrays.toString(indexes));
}
public static int[] indexesOf(String s, String flag) {
int flagLen = flag.length();
String current = s;
int[] res = new int[s.length()];
int count = 0;
int base = 0;
while(current.contains(flag)) {
int index = current.indexOf(flag);
res[count] = index + base;
base += index + flagLen;
current = current.substring(current.indexOf(flag) + flagLen, current.length());
++ count;
}
return Arrays.copyOf(res, count);
}
}
A class for splitting strings I came up with. A short test is provided at the end.
SplitStringUtils.smartSplitToShorterStrings(String str, int maxLen, int maxParts) will split by spaces without breaking words, if possible, and if not, will split by indexes according to maxLen.
Other methods provided to control how it is split: bruteSplitLimit(String str, int maxLen, int maxParts), spaceSplit(String str, int maxLen, int maxParts).
public class SplitStringUtils {
public static String[] smartSplitToShorterStrings(String str, int maxLen, int maxParts) {
if (str.length() <= maxLen) {
return new String[] {str};
}
if (str.length() > maxLen*maxParts) {
return bruteSplitLimit(str, maxLen, maxParts);
}
String[] res = spaceSplit(str, maxLen, maxParts);
if (res != null) {
return res;
}
return bruteSplitLimit(str, maxLen, maxParts);
}
public static String[] bruteSplitLimit(String str, int maxLen, int maxParts) {
String[] bruteArr = bruteSplit(str, maxLen);
String[] ret = Arrays.stream(bruteArr)
.limit(maxParts)
.collect(Collectors.toList())
.toArray(new String[maxParts]);
return ret;
}
public static String[] bruteSplit(String name, int maxLen) {
List<String> res = new ArrayList<>();
int start =0;
int end = maxLen;
while (end <= name.length()) {
String substr = name.substring(start, end);
res.add(substr);
start = end;
end +=maxLen;
}
String substr = name.substring(start, name.length());
res.add(substr);
return res.toArray(new String[res.size()]);
}
public static String[] spaceSplit(String str, int maxLen, int maxParts) {
List<Integer> spaceIndexes = findSplitPoints(str, ' ');
List<Integer> goodSplitIndexes = new ArrayList<>();
int goodIndex = -1;
int curPartMax = maxLen;
for (int i=0; i< spaceIndexes.size(); i++) {
int idx = spaceIndexes.get(i);
if (idx < curPartMax) {
goodIndex = idx;
} else {
goodSplitIndexes.add(goodIndex+1);
curPartMax = goodIndex+1+maxLen;
}
}
if (goodSplitIndexes.get(goodSplitIndexes.size()-1) != str.length()) {
goodSplitIndexes.add(str.length());
}
if (goodSplitIndexes.size()<=maxParts) {
List<String> res = new ArrayList<>();
int start = 0;
for (int i=0; i<goodSplitIndexes.size(); i++) {
int end = goodSplitIndexes.get(i);
if (end-start > maxLen) {
return null;
}
res.add(str.substring(start, end));
start = end;
}
return res.toArray(new String[res.size()]);
}
return null;
}
private static List<Integer> findSplitPoints(String str, char c) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
list.add(i);
}
}
list.add(str.length());
return list;
}
}
Simple test code:
public static void main(String[] args) {
String [] testStrings = {
"123",
"123 123 123 1123 123 123 123 123 123 123",
"123 54123 5123 513 54w567 3567 e56 73w45 63 567356 735687 4678 4678 u4678 u4678 56rt64w5 6546345",
"1345678934576235784620957029356723578946",
"12764444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444",
"3463356 35673567567 3567 35 3567 35 675 653 673567 777777777777777777777777777777777777777777777777777777777777777777"
};
int max = 35;
int maxparts = 2;
for (String str : testStrings) {
System.out.println("TEST\n |"+str+"|");
printSplitDetails(max, maxparts);
String[] res = smartSplitToShorterStrings(str, max, maxparts);
for (int i=0; i< res.length;i++) {
System.out.println(" "+i+": "+res[i]);
}
System.out.println("===========================================================================================================================================================");
}
}
static void printSplitDetails(int max, int maxparts) {
System.out.print(" X: ");
for (int i=0; i<max*maxparts; i++) {
if (i%max == 0) {
System.out.print("|");
} else {
System.out.print("-");
}
}
System.out.println();
}
This is a java 8 solution.
public int[] solution (String s, String subString){
int initialIndex = s.indexOf(subString);
List<Integer> indexList = new ArrayList<>();
while (initialIndex >=0){
indexList.add(initialIndex);
initialIndex = s.indexOf(subString, initialIndex+1);
}
int [] intA = indexList.stream().mapToInt(i->i).toArray();
return intA;
}
This can be done by iterating myString and shifting fromIndex parameter in indexOf():
int currentIndex = 0;
while (
myString.indexOf(
mySubstring,
currentIndex) >= 0) {
System.out.println(currentIndex);
currentIndex++;
}
Try this
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(StringUtils.countMatches(str, findStr));