iterationsubstringapache-stringutils

How to substring based on a specific characters through iteration?


I have this following string

String oldStr = ".abc.def.ghi.klm.";

How do I retrieve the substring and put into another string using a loop?

for (int i = 0; i < oldStr.length(); ++i) {
   String newStr = doSomethingMethod("oldStr");
}

where oldStr should be "abc", "def", "ghi", "klm" recursively

I tried to use StringUtils.subStringBetween(oldStr, ".", ".") but that only handle the first substring. Any help is greatly appreciated.


Solution

  • I am not sure what results your looking for but i would just use the Split method with the period and get a string array. now each element is a new string.

    var results = oldstring.Split('.');
    

    this gives you an array... "abc", "def", "ghi" ...

    if you simply want to remove the periods then you can just use the Replace method

    var newstring = oldstring.Replace(".","");
    

    now you have a string "abcdefghjklm"