0

I know the split can be done with split functionality of java. I did that like in the below code

String[] sArr = name.split("[\\s.]+");
String newStr = "";
for (int i = 0; i < sArr.length; i++){
     newStr = newStr + " " + mymethod(sArr[i]);     
}

What i actually want to do is all the words in the string must pass through mymethod and reform the string. But on reforming i dont want to loss the dots and spaces which is actually there. For example Mr. John will remove the dot after reforming and would change in to Mr John which i don't want. So how to reform my string without losing anything in that actual string, but also each word to pass through mymethod also. Thanks in advance!

Socowi
  • 25,550
  • 3
  • 32
  • 54
Mohammed Javad
  • 629
  • 8
  • 18

1 Answers1

0

Iterate over String using any loop char by char and find for . and space char, Then by using substring() method split Original string by storing index.

Code:-

List<String> arr=new ArrayList<String>();     // Array to hold splitted tokens
        String str="Mr. John abc. def";
        int strt=0; 
        int end=0;
        for (int i = 0; i < str.length(); i++) {  //Iterate over Original String
            if (str.charAt(i)=='.')               // Match . character
            {   
                end=i;
                arr.add(str.substring(strt,end));
                arr.add(str.charAt(i)+"");
                strt=i+1;
            }
            if (str.charAt(i)==' ')           // Match space character
            {   
                end=i;
                if (strt!=end)             // check if space is not just after . character
                arr.add(str.substring(strt,end));
                strt=i+1;
            }
        }
        System.out.println(arr);
Tarun
  • 986
  • 6
  • 19