Java split string with combinations - java

My input string is
element1-element2-element3-element4a|element4b-element5-
Expected output is
element1-element2-element3-element4a-element5-
element1-element2-element3-element4b-element5-
So the dash (-) is the delimiter and the pipe (|) indicates two alternative elements for a position.
I am able to generate combinations for input containing a single pipe:
ArrayList<String> finalInput = new ArrayList<String>();
String Input = getInputPath();
StringBuilder TempInput = new StringBuilder();
if(Input.contains("|")) {
String[] splits = Input.split("\\|", 2);
TempInput.append(splits[0]+"-"+splits[1].split("-", 2)[1]);
finalInput.add(TempInput.toString());
TempInput = new StringBuilder();
String[] splits1 = new StringBuilder(Input).reverse().toString().split("\\|", 2);
finalInput.add(TempInput.append(splits1[0]+"-"+splits1[1].split("-", 2)[1]).reverse().toString());
}
But this logic fails if there are multiple pipe symbols.
How to split a String on the last occurrance only?
Is there any efficient way to use split String with combinations?
Input:
element1-element2-element3-element4a|element4b-element5-element6a|element6b
Output:
element1-element2-element3-element4a-element5-element6a
element1-element2-element3-element4b-element5-element6a
element1-element2-element3-element4a-element5-element6b
element1-element2-element3-element4b-element5-element6b

Recursion helps.
public static void main(String[] args) {
produce("element1-element2-element3-element4a|element4b"
+ "-element5-element6a|element6b");
}
private static void produce(String input) {
String[] sequence = input.split("-");
String[][] elements = new String[sequence.length][];
for (int i = 0; i < sequence.length; ++i) {
elements[i] = sequence[i].split("\\|");
}
List<String> results = new ArrayList<>();
walk(results, elements, 0, new StringBuilder());
}
private static void walk(List<String> results, String[][] elements,
int todoIndex, StringBuilder done) {
if (todoIndex >= elements.length) {
results.add(done.toString());
System.out.println(done);
return;
}
int doneLength = done.length();
for (String alternative : elements[todoIndex]) {
if (done.length() != 0) {
done.append('-');
}
done.append(alternative);
walk(results, elements, todoIndex + 1, done);
done.setLength(doneLength); // Undo
}
}
The String.split method is used twice to get a navigatable String[][]. And to build a final String a StringBuilder is used.

You can use StringTokenizer in Java. Basically it makes tokens of the string.
public StringTokenizer(String str, String delim)
Here's an example:
String msg = "http://100.15.111.60:80/";
char tokenSeparator= ':';
StringTokenizer st = new StringTokenizer(msg, tokenSeparator + "");
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}

I have write a demo for you as what I comment after your post, the code may be ugly, but it works
public class TestSplit {
//define a stringList hold our result.
private static List<String> stringList = new ArrayList<String>();
//this method fork the list array when we meet a "|"
public static void forkStringList(){
List<String> tmpList = new ArrayList<String>();
for(String s: stringList){
tmpList.add(s);
}
stringList.addAll(tmpList);
}
//when we meet "|" split two elems, should add it to
//the string list half-half
public static void addTowElems(String s1, String s2){
for(int i=0;i<stringList.size()/2;i++){
stringList.set(i,stringList.get(i)+s1);
}
for(int i = stringList.size()/2;i<stringList.size();i++){
stringList.set(i,stringList.get(i)+s2);
}
}
// if not meet with a "|" just add elem to everyone of the stringlist
public static void addOneElem(String s){
for(int i=0;i<stringList.size();i++){
stringList.set(i,stringList.get(i)+s);
}
}
public static void main(String[] argvs){
//to make *fork* run, we must make sure there is a "init" string
//which is a empty string.
stringList.add("");
// this is your origin string.
String input = "a-b-c-d|e-f";
for (String s: input.split("\\-")){
if(s.contains("|")){
//when meet with "|", first fork the stringlist
forkStringList();
// then add them separately
addTowElems(s.split("\\|")[0],s.split("\\|")[1]);
}else {
// else just happily add the elem to every one
// of the stringlist
addOneElem(s);
}
}
//checkout the result, should be expected.
System.out.println(stringList);
}
}

Here's my iterative solution:
import java.util.*;
public class PathParser {
private static final String DELIMINATOR_CONCAT = "-";
private static final String DELIMINATOR_OPTION = "|";
private List<String> paths;
private List<String> stack;
private List<String> parse(final String pathSpec) {
stack = new ArrayList<String>();
paths = new ArrayList<String>();
paths.add("");
final StringTokenizer tok = createStringTokenizer(pathSpec);
while (tok.hasMoreTokens()) {
final String token = tok.nextToken();
parseToken(token);
}
if (!stack.isEmpty()) {
updatePaths();
}
return paths;
}
private void parseToken(final String token) {
if (DELIMINATOR_CONCAT.equals(token)) {
updatePaths();
} else if (DELIMINATOR_OPTION.equals(token)) {
// nothing to do
} else {
stack.add(token);
}
}
private void updatePaths() {
final List<String> originalPaths = new ArrayList<String>(paths);
paths.clear();
while (stack.size() > 0) {
paths.addAll(createNewPaths(originalPaths));
}
}
private List<String> createNewPaths(final List<String> originalPaths) {
final List<String> newPaths = new ArrayList<String>(originalPaths);
addPart(newPaths, stack.remove(0));
addPart(newPaths, DELIMINATOR_CONCAT);
return newPaths;
}
private void addPart(final List<String> paths, final String part) {
for (int i = 0; i < paths.size(); i++) {
paths.set(i, paths.get(i) + part);
}
}
private StringTokenizer createStringTokenizer(final String pathSpec) {
final boolean returnDelimiters = true;
final String delimiters = DELIMINATOR_CONCAT + DELIMINATOR_OPTION;
return new StringTokenizer(pathSpec, delimiters, returnDelimiters);
}
public static void main(final String[] args) {
final PathParser pathParser = new PathParser();
final String input = "element1-element2-element3-element4a|element4b|element4c-element5-element6a|element6b|element6c";
System.out.println("Input");
System.out.println(input);
System.out.println();
final List<String> paths = pathParser.parse(input);
System.out.println("Output");
for (final String path : paths) {
System.out.println(path);
}
}
}
Output:
Input
element1-element2-element3-element4a|element4b-element5-element6a|element6b
Output
element1-element2-element3-element4a-element5-element6a-
element1-element2-element3-element4b-element5-element6a-
element1-element2-element3-element4a-element5-element6b-
element1-element2-element3-element4b-element5-element6b-

This helps to acheive the same..
public class MultiStringSplitter {
public static void main(String arg[]) {
String input = "a-b|c-d|e-f|g-h";
String[] primeTokens = input.split("-");
String[] level2Tokens = null;
String element = "";
String level2element = "";
ArrayList stringList = new ArrayList();
ArrayList level1List = new ArrayList();
ArrayList level2List = new ArrayList();
for (int i = 0; i < primeTokens.length; i++) {
// System.out.print(primeTokens[i]);
if (primeTokens[i].contains("|")) {
level2Tokens = primeTokens[i].split("\\|");
for (int j = 0; j < level2Tokens.length; j++) {
for (int k = 0; k < stringList.size(); k++) {
element = (String) stringList.get(k);
level2element = element + level2Tokens[j];
level2List.add(level2element);
}
}
stringList = new ArrayList();
for (int w = 0; w < level2List.size(); w++) {
stringList.add(level2List.get(w));
}
level2List = new ArrayList();
}
else {
if (stringList.size() > 0) {
for (int z = 0; z < stringList.size(); z++) {
element = (String) stringList.get(z);
element = element + primeTokens[i];
level1List.add(element);
}
stringList = new ArrayList();
for (int w = 0; w < level1List.size(); w++) {
stringList.add(level1List.get(w));
}
level1List = new ArrayList();
}
else {
element = element + primeTokens[i];
if (stringList.size() == 0) {
stringList.add(element);
}
}
}
}
for (int q = 0; q < stringList.size(); q++) {
System.out.println(stringList.get(q));
}
}
}
Input : a-b|c-d|e-f|g-h
Output:
abdfh
acdfh
abefh
acefh
abdgh
acdgh
abegh
acegh

Related

Remove Duplicates combination from List

Members of List<String> as follows
U1,U2
U2,U1
U3,U2
U2,U3
U3,U4
Output should be
U1,U2
U2,U3
U3,U4
Code Tried
import java.util.*;
public class Main {
static List<String> opList = new ArrayList<String>();
static List<String> FinalopList = new ArrayList<String>();
static List<String> processStrings(List<String> friends) {
for (int i = 0; i < friends.size(); i++) {
StringBuilder newInp = new StringBuilder();
boolean statusOpp = false;
boolean statusSimilar = false;
String inp = opList.get(i);
String[] splitFriends = inp.split(",");
newInp.append(splitFriends[1]).append(",").append(splitFriends[0]).toString();
System.out.println("newInp:" + newInp);
for (int j = 0; j < friends.size(); j++) {
if (friends.get(j).contains(newInp.toString())) {
statusOpp = true;
}
else if (friends.get(j).contains(inp)) {
statusSimilar = true;
}
}
if (statusOpp) {
FinalopList.add(inp.toString());
System.out.println(inp.toString());
}
else {
FinalopList.add(inp.toString());
System.out.println(inp.toString());
}
}
return FinalopList;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number of Friends Combinations separated by comma");
int inp = sc.nextInt();
for (int i = 0; i < inp; i++) {
opList.add(sc.next());
}
processStrings(opList);
}
}
Stuck in get Unique values.
Please suggest
You could check whether the new list already contains any combination of elements and add it to the list otherwise.
static List<String> opList = new ArrayList<String>();
static List<String> finalopList = new ArrayList<String>();
static List<String> processStrings(List<String> friends) {
for (int i = 0; i < friends.size(); i++) {
StringBuilder newInp = new StringBuilder();
String inp = opList.get(i);
String[] splitFriends = inp.split(",");
String newInpStr = newInp.append(splitFriends[1]).append(",").append(splitFriends[0]).toString();
if(!finalopList.contains(inp) && !finalopList.contains(newInpStr)) {
finalopList.add(inp);
}
}
System.out.println(finalopList);
return finalopList;
}

What is the program for string conversion like a2b4c5 into aabbbbccccc in java language?

i got this program by someone but but i could not handle it please anyone tell me how to handle it in a easy way. Thank you
public class Program {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "a11b4c5";
System.out.println(getAnswerByPassingString(str));
}
public static String getAnswerByPassingString(String str) {
String number = "";
String letter = "";
String resStr = "";
ArrayList<String> stringList = new ArrayList<String>();
ArrayList<String> numbersList = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
char a = str.charAt(i);
if (Character.isDigit(a)) {
number = number + a;
//numbersList.add("" + a);
} else {
letter = letter + a;
stringList.add("" + a);
}
}
Matcher m = Pattern.compile("\\d+").matcher(str);
//List<Integer> numbers = new ArrayList<Integer>();
while(m.find()) {
numbersList.add(""+Integer.parseInt(m.group()));
}
// System.out.println(numbers);
for (int i = 0; i < stringList.size(); i++) {
int j = Integer.parseInt(numbersList.get(i));
String concatStr = stringList.get(i);
int count = 0;
for (int k = 1; k <= j; k++) {
concatStr = concatStr + concatStr;
if (k == j)
count = k;
}
resStr = resStr + concatStr.substring(0, count);
concatStr = "";
}
return resStr;
}
}
Using the below code you can get numbers from the string :
public static void main(String[] args) {
String str = "a2bc45cd5";
Matcher m = Pattern.compile("\\d+").matcher(str);
List<Integer> numbers = new ArrayList<Integer>();
while(m.find()) {
numbers.add(Integer.parseInt(m.group()));
}
System.out.println(numbers);
Matcher m1 = Pattern.compile("[A-z]+").matcher(str);
List<String> string = new ArrayList<String>();
while(m1.find()) {
string.add(m1.group());
}
System.out.println(string);
}
//Output :
[2, 45, 5] // For numbers
[a, bc, cd] // For string
After get the number using loop you achieve your output result.

Java array I need your thought

Given an array of strings, return another array containing all of its longest strings.
For (String [] x = {"serm", "aa", "sazi", "vcd", "aba","kart"};)
output will be
{"serm", "sazi" , "kart"}.
The following code is wrong, What can I do to fix it.
public class Tester {
public static void main(String[] args) {
Tester all = new Tester();
String [] x = {"serm", "aa", "sazi", "vcd", "aba","kart"};
String [] y = all.allLongestStrings(x);
System.out.println(y);
}
String[] allLongestStrings(String[] input) {
ArrayList<String> answer = new ArrayList<String>(
Arrays.asList(input[0]));
for (int i = 1; i < input.length; i++) {
if (input[i].length() == answer.get(0).length()) {
answer.add(input[i]);
}
if (input[i].length() > answer.get(0).length()) {
answer.add(input[i]);
}
}
return answer.toArray(new String[0]);
}
}
I will give you solution, but as it homework, it will be only sudo code
problem with your solution is, you are not finging longest strings, but strings same size or bigger than size of first element
let helper = []
let maxLength = 0;
for each string in array
if (len(string) >maxLength){
maxLength = len(string);
clear(helper)
}
if (len(string) == maxLength)
helper.add(string)
}
return helper;
You can try below code
private static String[] solution(String[] inputArray) {
int longestStrSize = 0;
List<String> longestStringList = new ArrayList<>();
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] != null) {
if (longestStrSize <= inputArray[i].length()) {
longestStrSize = inputArray[i].length();
longestStringList.add(inputArray[i]);
}
}
}
final int i = longestStrSize;
return longestStringList.stream().filter(x -> x.length() >= i).collect(Collectors.toList()).stream()
.toArray(String[]::new);
}

split string and store in arraylist

I want to split the below mentioned string and save it in two seperate arraylist like state and city
public class RoundValue {
public static void main(String args[]) {
String firstset = null;
String city = "Tamilnadu;chennai-madurai-salem::Kerala;cochin-tiruvandrum-calicut";
ArrayList<String> mState = new ArrayList<String>();
ArrayList<String> mCity = new ArrayList<String>();
HashMap<String, List<String>> hashsplit = new HashMap<String, List<String>>();
List<String> splitword1 = Arrays.asList(city.split("::"));
if (splitword1.size() > 0) {
for (int i = 0; i < splitword1.size(); i++) {
firstset = splitword1.get(i);
List<String> firststate = Arrays.asList(firstset.split("-"));
if (firststate.size() > 0) {
for (int j = 0; j < firststate.size(); j++) {
String firstcity = firststate.get(j);
List<String> secondcity = Arrays.asList(firstcity.split(";"));
if (secondcity.size() > 0) {
for (int k = 0; k < secondcity.size(); k++) {
String septcity = secondcity.get(k);
System.out.println("septcity Splitted:" + septcity);
}
}
}
}
}
}
}
}
I have splitted each and every character, but i have to store state in seperate list and city in seperate list
Step 1: Split your given string input as Arrays.asList(city.split("::"));, you alresy did it.
Step 2: Split each list in to array like, example Tamilnadu;chennai-madurai-salem using String both[]=string.split(";"); here you will get seperated state and cities. like both[0] is State. both[1] is chennai-madurai-salem
Step 3: Split the cities string in both[1] usig both[1].split("-")
So Demo code I have given as below. You can modify.
public static void main(String[] args) {
String city = "Tamilnadu;chennai-madurai-salem::Kerala;cochin-tiruvandrum-calicut";
ArrayList<String> mState = new ArrayList<String>();
ArrayList<String> mCity = new ArrayList<String>();
List<String> bothList= Arrays.asList(city.split("::"));
for (String string : bothList) {
String both[]=string.split(";");
String state=both[0];
List<String> tempCityList=Arrays.asList(both[1].split("-"));
mState.add(state);
mCity.addAll(tempCityList);
}
System.out.println("Your states");
for (String string : mState) {
System.out.print(string+" ");
}
System.out.println("\nYour cities");
for (String string : mCity) {
System.out.print(string+" ");
}
}
Here is the example
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by Prasad on 6/17/2014.
*/
public class stack {
public static void main(String[] args) {
String s="Tamilnadu;chennai-madurai-salem::Kerala;cochin-tiruvandrum-calicut";
ArrayList<String> x1=new ArrayList<String>();
ArrayList<String> x2=new ArrayList<String>();
String string[]=s.split("::");
for(String y:string){
try{
String[] temp=y.split(";");
x1.add(temp[0]);
x2.add(temp[1]);
}catch(Exception e){}
}
System.out.println(x1.toString());
System.out.println(x2.toString());
}
}

java delete reverse string in list

I have struct Array or List String like:
{ "A.B", "B.A", "A.C", "C.A" }
and I want delete reverse string from list that end of only:
{ "A.B", "A.C" }
how type String use and how delete reverse String?
To reverse a string I recommend using a StringBuffer.
String sample = "ABC";
String reversed_sample = new StringBuffer(sample).reverse().toString();
To delete object form you ArrayList use the remove method.
String sample = "ABC";String to_remove = "ADS";
ArrayList<String> list = new ArrayList<Sample>();
list.add(to_remove);list.add(sample );
list.remove(to_remove);
You can get use of a HashMap to determine whether a string is a reversed version of the other strings in the list. And you will also need a utility function for reversing a given string. Take a look at this snippets:
String[] input = { "A.B", "B.A", "A.C", "C.A" };
HashMap<String, String> map = new HashMap<String, String>();
String[] output = new String[input.length];
int index = 0;
for (int i = 0; i < input.length; i++) {
if (!map.containsKey(input[i])) {
map.put(reverse(input[i]), "default");
output[index++] = input[i];
}
}
A sample String-reversing method could be like this:
public static String reverse(String str) {
String output = "";
int size = str.length();
for (int i = size - 1; i >= 0; i--)
output += str.charAt(i) + "";
return output;
}
Output:
The output array will contain these elements => [A.B, A.C, null, null]
A code is worth thousand words.....
public class Tes {
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
arr.add("A.B");
arr.add("B.A");
arr.add("A.C");
arr.add("C.A");
System.out.println(arr);
for (int i = 0; i < arr.size(); i++) {
StringBuilder str = new StringBuilder(arr.get(i));
String revStr = str.reverse().toString();
if (arr.contains(revStr)) {
arr.remove(i);
}
}
System.out.println(arr);
}
}
You can do this very simply in O(n^2) time. Psuedocode:
For every element1 in the list:
For every element2 in the list after element1:
if reverse(element2).equals(element1)
list.remove(element2)
In order to make your life easier and prevent ConcurrentModificationException use Iterator. I won't give you the code because it's a good example to learn how to properly use iterators in Java.
Reverse method:
public String reverse(String toReverse) {
return new StringBuilder(toReverse).reverse().toString();
}
Edit: another reverse method:
public String reverse(String toReverse) {
if (toReverse != null && !toReverse.isEmpty) {
String[] elems = toReverse.split(".");
}
StringBuilder reversedString = new StringBuilder("");
for (int i = elems.length - 1; i >= 0; i++) {
reversedString.append(elems[i]);
reversedString.append(".");
}
return reversedString.toString();
}
Check this
public static void main(String arg[]){
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
List<String> strList = new ArrayList<String>();
strList.add("A.B");
strList.add("B.A");
strList.add("A.C");
strList.add("C.A");
Iterator<String> itr = strList.iterator();
while(itr.hasNext()){
String [] split = itr.next().toUpperCase().split("\\.");
if(str.indexOf(split[0])>str.indexOf(split[1])){
itr.remove();
}
}
System.out.println(strList);
}
output is
[A.B, A.C]
You can iterate the list while maintaining a Set<String> of elements in it.
While you do it - create a new list (which will be the output) and:
if (!set.contains(current.reverse())) {
outputList.append(current)
set.add(current)
}
This solution is O(n*|S|) on average, where n is the number of elements and |S| is the average string length.
Java Code:
private static String reverse(String s) {
StringBuilder sb = new StringBuilder();
for (int i = s.length()-1 ; i >=0 ; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}
private static List<String> removeReverses(List<String> arr) {
Set<String> set = new HashSet<String>();
List<String> res = new ArrayList<String>();
for (String s : arr) {
if (!set.contains(reverse(s))) {
res.add(s);
set.add(s);
}
}
return res;
}
public static void main(String[]args){
String[] arr = { "a.c" , "b.c", "c.a", "c.b" };
System.out.println(removeReverses(arr));
}
will yield:
[a.c, b.c]

Categories