Home > OS >  Split string and print the string in size of array
Split string and print the string in size of array

Time:08-09

Hello this is my input String

"Hello A1:A2:A3 your age is 21:22:23 and you belongs to India:India:Nepal thanks for visiting"

And I wants below as output

"Hello A1 your age is 21 and you belongs to India thanks for visiting" 
"Hello A2 your age is 22 and you belongs to India thanks for visiting" 
"Hello A3 your age is 23 and you belongs to Nepal thanks for visiting" 

CodePudding user response:

You could use something like this:

final String s = "Hello A1:A2:A3 your age is 21:22:23 and you belongs to India:India:Nepal thanks for visiting";
// split the string into words and split the colon words
final List<String[]> words = Arrays.stream(s.split(" "))
    .map((word) -> word.split(":"))
    .collect(Collectors.toList());
// find the longest colon word collection
final int max = words.stream()
    .map((w)->w.length)
    .max(Comparator.comparingInt(w -> w))
    .get();
// join back up and print the combinations
IntStream.range(0, max).forEach((i) ->
    System.out.println(String.join(" ", words.stream()
        .map((w) -> w[i % w.length])
        .collect(Collectors.toList())))
);

CodePudding user response:

I have tried so far this solution and that works but if give me output response time as 3 ms and I want better solution than below

    String originalString = "Hello A1:A2:A3 your age is 21:22:23 and you belongs to India:India:Nepal thanks for visiting";
    String[] originalStringArray = originalString.split(" ");
    String duplicateString = originalString;

    Map<String, List<String>> lMap = new LinkedHashMap<>();

    for (String s11 : originalStringArray) {
        if (s11.contains(":")) {
            lMap.put(s11, Arrays.asList(s11.split(":")));
        }
    }
    for (String lKey : lMap.keySet()) {
        if (duplicateString.contains(lKey)) {
            List<String> lValueList = lMap.get(lKey);
            int lIndex = 1;
            for (String lValue : lValueList) {
                int length = lKey.length();
                int inputLength = duplicateString.length();
                int startingIndexofTheStringToReplace = duplicateString.indexOf(lKey);
                duplicateString = duplicateString.substring(0, startingIndexofTheStringToReplace)   lValue
                          duplicateString.substring(startingIndexofTheStringToReplace   length, inputLength);
                if (lIndex < lValueList.size() && !duplicateString.contains(lKey)) {
                    duplicateString = duplicateString   originalString;
                }
                lIndex  ;
            }
        }

    }
    originalString = duplicateString;
    System.out.println(originalString);

CodePudding user response:

As mentioned in the comments, you could use string.split(" ") to get the words, then simply loop the returned array and print each word. When you come to a word that contains : you can further split it with the : character for each line and print out the corresponding token.

You mentioned that you want a solution that completes faster, well using the above logic with String.split(...) and two loops, we can get the result in a quarter of the time that your current code takes:

//Track the time
final long START = System.nanoTime();
//The input
String input = "Hello A1:A2:A3 your age is 21:22:23 and you belongs to India:India:Nepal thanks for visiting";
//Total options
int options = 0;
//Track the option being printed
int option = 0;
//Track when printing is finished
boolean complete = false;
//Split the words
String[] words = input.split(" ");

//Loop the words to find how many tokens you have
for (String word : words)
{
    //Check if the word contains the token and find out how many options there are
    if(word.contains(":")){
        //Set the options so that we know how many lines to print
        options = word.split(":").length;
        break;
    }
}

//Print a line for each option
for (int i = 0; i < options; i  )
{
    //Track when the flag is found for each line (You could do this once if you want max efficiency)
    boolean flag = false;
    
    //Loop the words
    for (String word : words)
    {
    //Check if the word contains the flag and print it
    if(word.contains(":")){
        System.out.print(word.split(":")[option] " ");
    }
    //Print the narmal words
    else
        System.out.print(word " ");
    }
    //Move to the next line
    System.out.println();
    option  ;
}
//Print the time taken
final long END = System.nanoTime();
System.out.println("Run time: "   ((END - START) / 1e 9)   " seconds");

And the output is as follows an my slow PC from 2012:

Hello A1 your age is 21 and you belongs to India thanks for visiting 
Hello A2 your age is 22 and you belongs to India thanks for visiting 
Hello A3 your age is 23 and you belongs to Nepal thanks for visiting 
Run time: 0.0065375 seconds

Which is quite a bit faster than your code on the same system:

Run time: 0.024666099 seconds

Which makes the above code is about 4x faster than your solution with a HashMap. On a modern PC the runtime should be quite a bit better than my results.

CodePudding user response:

You could look for the pattern and collect the matches to a list and use a String#replace while iterating over the matches

String arr = "Hello A1:A2:A3 your age is 21:22:23 and you belongs to India:India:Nepal thanks for visiting";

Pattern p = Pattern.compile("\\b\\w :\\w :\\w \\b");

List<String> matches = p.matcher(arr)
                        .results()
                        .map(MatchResult::group)
                        .collect(Collectors.toList());

int length = matches.get(0).split(":").length;

for (int i = 0; i < length; i  ) {
    String res = arr;
    for (String m : matches) {
        res = res.replace(m, m.split(":")[i]);
    }
    System.out.println(res);
}

CodePudding user response:

package com.harshlata;

public class StringSolution {

static String s = "Hello A1:A2:A3 your age is 21:22:23 and you belongs to India:India:Nepal thanks for visiting";

public static void main(String[] args) {
    String names[] = null;
    String age[] = null;
    String place[] = null;
    StringBuilder sb = null;
    String[] subString = s.split(" ");
    // each substring logic
    for (int i = 0; i < subString.length; i  ) {
        if (subString[i].contains(":")) {
            if (subString[i - 1].equals("Hello")) {
                names = subString[i].split(":");
            } else if (subString[i - 1].equals("is")) {
                age = subString[i].split(":");
            } else if (subString[i - 1].equals("to")) {
                place = subString[i].split(":");
            }
        }
    }

    // replace original content with current string
    for (int i = 0; i < names.length; i  ) {
        sb = new StringBuilder();
        for (int j = 0; j < subString.length; j  ) {
            if (subString[j].contains(":") && j >= 1 && subString[j - 1].equals("Hello")) {
                sb = sb.append(" "   names[i]);
            } else if (subString[j].contains(":") && j >= 1 && subString[j - 1].equals("is")) {
                sb = sb.append(" "   age[i]);
            } else if (subString[j].contains(":") && j >= 1 && subString[j - 1].equals("to")) {
                sb = sb.append(" "   place[i]);
            } else {
                sb = sb.append(" "   subString[j]);
            }
        }
        System.out.println(sb);
    }
}

}

Output: Hello A1 your age is 21 and you belongs to India thanks for visiting Hello A2 your age is 22 and you belongs to India thanks for visiting Hello A3 your age is 23 and you belongs to Nepal thanks for visiting

  • Related