Java's String
class is immutable. String.concat()
will return the concatenation as a new String
object.
You can either use retVal = retVal.concat(...)
, or use a StringBuilder
.
The following works:
class MyTesting
{
public static void main (String[] args) throws java.lang.Exception
{
capitalizeEveryNthWord("this is a sentence that is being tested", 3, 3);
}
// Take a single-spaced <sentence>, and capitalize every <n> word starting with <offset>.
public static String capitalizeEveryNthWord(String sentence, Integer offset, Integer n) {
String[] parts = sentence.split(" ");
String retVal = "";
for (int idx = 0; idx < offset; idx++)
{
retVal += parts[idx] + " ";
}
for (int idx = offset; idx < parts.length; idx++)
{
if ((idx - offset) % n == 0) // added parantheses
{
retVal += Character.toUpperCase(parts[idx].charAt(0)) + parts[idx].substring(1) + " "; // make the first character uppercase.
}
else
{
retVal += parts[idx] + " ";
}
}
System.out.println(retVal);
return retVal;
}
}
A more efficient approach would be something like:
public static String capitalizeEveryNthWord(String sentence, Integer offset, Integer n) {
StringBuilder sb = new StringBuilder(sentence);
int wordIdx = 0;
boolean newWord = true;
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
if (c == ' ') {
wordIdx++; // assumes single space between words.
newWord = true;
} else if (newWord) {
if (wordIdx >= offset && (wordIdx - offset) % n == 0) {
sb.setCharAt(i, Character.toUpperCase(c));
}
newWord = false;
}
}
return sb.toString();
}
This second approach only allocates one buffer which is then modified in-place to capitalize words. The previous approach allocates new String
objects with every call to +=
(this can occasionally be optimized away by compilers but it's not guaranteed, as far as I know).