The following code will split the string into chunks, each of length ‘nchars’ (except potentially the last chunk)
int len = string.length();
for (int i=0; i<len; i+=nchars)
{
String part = string.substring(i, Math.min(len, i + nchars)));
}
Another more exotic option uses regular expression and the spit() method. The number of dots in the regexp controls the length of each part.
// Splits string into 3 character long pieces.
String[] parts = string.split("(?<=\\G...)");
See how to fill a string with a character for how to dynamically generate a regexp for any number of characters. Though I’d probably go with the first method.
written by objects
\\ tags: regexp, split, string, substring
Java 1.5 added a replace() method that could be used to replace all occurrences of a string wiuth another string
s = s.replace(" ", "");
Prior to 1.5 you can use a regular expression with the replaceAll() method to achieve that.
s = s.replaceAll(" ", "");
// Or to replace all whitespace
s = s.replaceAll("\\s", "");
Let us know if you need a different solution.
written by objects
\\ tags: regexp, spaces, string
By default regexp matching is case sensitive. To make it case insensitive use the CASE_INSENSITIVE flag in your regex. It can be embedded in the regex string using (?i).
String s = "aBcXYZABCdefAbc";
String replaced = s.replaceAll("(?i)abc", "123");
written by objects
\\ tags: regexp, string