Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, How to split String with shifting

How can I split a string by 2 characters with shifting. For example;

My string is = todayiscold

My target is: "to","od","da","ay","yi","is","sc","co","ol","ld"

but with this code:

Arrays.toString("todayiscold".split("(?<=\\G.{2})")));

I get: `"to","da","yi","co","ld"

anybody helps?

like image 411
reigeki Avatar asked Aug 01 '13 16:08

reigeki


People also ask

How do you shift a string in Java?

Create an array of characters from the input string. Traverse the String array from the start (index 0) to end (n-1, where n is the length of an array). Perform the shift operation on each and every character of an array. Convert modified array of characters to string and return it.

How do I split a string into multiple places?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.

How do I split a string without a separator?

Q #4) How to split a string in Java without delimiter or How to split each character in Java? Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.


2 Answers

Try this:

        String e = "example";
        for (int i = 0; i < e.length() - 1; i++) {
            System.out.println(e.substring(i, i+2));
        }
like image 150
nkukhar Avatar answered Oct 21 '22 15:10

nkukhar


Use a loop:

String test = "abcdefgh";
List<String> list = new ArrayList<String>();
for(int i = 0; i < test.length() - 1; i++)
{
   list.add(test.substring(i, i + 2));
}
like image 22
D-Rock Avatar answered Oct 21 '22 16:10

D-Rock