Nikola Despotoski
Nikola Despotoski

Reputation: 50588

Split string into several two character strings

I have this string 8S8Q4D1SKCQC2C4S6H4C6DJS2S1C6C

How can I split this string into substrings that consist of 2 characters per substring? I'm confused because I cannot find a delimiter to split them.

Upvotes: 3

Views: 21578

Answers (4)

Phil
Phil

Reputation: 1

for (int i = 0; i < a[2].Length; i++)
{
    string ss = (8S8Q4D1SKCQC2C4S6H4C6DJS2S1C6C).Substring(i, 2);
    Console.Write(ss);
    i++; 
}

Upvotes: -2

KitsuneYMG
KitsuneYMG

Reputation: 12901

System.out.println(Arrays.toString(
    "8S8Q4D1SKCQC2C4S6H4C6DJS2S1C6C".split("(?<=\\G.{2})")
));

Upvotes: 17

Mark
Mark

Reputation: 17182

Use the substring(int beginIndex, int endIndex) method of the String class.

Upvotes: 1

nybbler
nybbler

Reputation: 4841

You will have to do a split like this on your own. You could use something like substring in the following way:

public String[] customSplit(String src, int size) {
    Vector<String> vec = new Vector<String>();

    for(int i = 0; i < src.length(); i += size) {
        vec.add(src.substring(i, (i+size > src.length()) ? src.length() : i+size);
    }

    return vec.toArray(); 
}

Upvotes: 0

Related Questions