abhi
abhi

Reputation: 818

remove all occurrence of sub string from string other than first and last in java

is java have any option like remove all occurrence of a sub string from string other than 1st and last occurrence for example

String sdata=" vijay is 10 yr old. vijay is studying in 5th grade. vijay is excellent in sports.vijay like cricket "

i need a output like " vijay is 10 yr old. is studying in 5th grade. is excellent in sports.vijay like cricket "

that means removing second and third occurrence of vijay. does java have any inbuilt function for this?

Upvotes: 0

Views: 73

Answers (3)

John Paul
John Paul

Reputation: 782

As Jan say's it is quiet a specific thing. There are lots of Java methods and libraries but not that specific. So I've done you an example answer to show how you might go about this by iterating over the array, it does this.

  1. Goes through the char array and replaces an values that match the string you are searching.
  2. Places the first occurrence of the find string back in the main string.
  3. Places the last occurrence of the find string back in the main string.
  4. Removes all remaining occurrences of special character.

    private void start() {

    String origanlString = "vijay is 10 yr old. vijay is studying in 5th grade. vijay is excellent in sports. vijay like cricket.";
    String toFind = "vijay";
    char deliminator = 'X';     //      '\u0000'
    char[] orig = origanlString.toCharArray();
    char[] find = toFind.toCharArray();
    System.out.println("orig length:"+orig.length);
    System.out.println("find length:"+find.length+"\n");
    
    System.out.println("[0] ***"+String.valueOf(orig)+"***("+orig.length+")chars");
    
    //  1.  Iterate over the array to be searched
    for(int i=0;i<orig.length;i++){
    
        //  If letter found equals the first letter of the toFind array, then check the rest of the characters
        Boolean matchFound = true;
        if(find[0]==orig[i]){               
            wordCheckLoop:
            for(int x=0;x<find.length;x++){
                if(orig[i+x]!=find[x]){
                    matchFound = false;
                    break wordCheckLoop;
                }
            }
            //  Replace found string with place holders
            if(matchFound){
                for(int x=0;x<find.length;x++){
                    orig[i+x] = deliminator;
                }
            }
        }
    }
    System.out.println("[1] ***"+String.valueOf(orig)+"***("+orig.length+")chars");
    
    //  2.  Replace the first occurance
    int count = 0;
    Boolean firstInst = true;
    replaceFirst:
    for(int i=0;i<orig.length;i++){
        try{
            if(orig[i]==deliminator&&firstInst){
                orig[i]=find[count++];
                if(orig[i+1]!=deliminator){
                    firstInst = false;
                }
            }
        }catch(ArrayIndexOutOfBoundsException  ex){
            break replaceFirst;
        }
    }
    System.out.println("[2] ***"+String.valueOf(orig)+"***("+orig.length+")chars");
    
    //  3.  Replace the last occurance
    firstInst = true;
    count = find.length-1;
    replaceLast:
    for(int i=orig.length-1;i>0;i--){
        try{
            if(orig[i]==deliminator&&firstInst){
                orig[i]=find[count--];
                if(orig[i-1]!=deliminator){
                    firstInst=false;
                }
            }
        }catch(ArrayIndexOutOfBoundsException ex){
            System.out.println("ArrayIndexOutOfBoundsException");
            break replaceLast;
        }
    }
    System.out.println("[3] ***"+String.valueOf(orig)+"***("+orig.length+")chars");
    
    //  4.  Remove all remaining occurances of special charactor
    count = 0;
    for(int i=0;i<orig.length;i++){
        if(orig[i]==deliminator){
            count++;
        }
    }
    char[] tempArray = new char[orig.length-count];
    count = 0;
    for(int i=0;i<orig.length;i++){
        if(orig[i]!=deliminator){
            tempArray[count++] = orig[i];
        }
    }
    System.out.println("[4] ***"+String.valueOf(tempArray)+"***("+tempArray.length+")chars");
    }
    

Upvotes: 0

storm87
storm87

Reputation: 59

No it doesn't. You could try something like this:

String s = "vijay is 10 yr old. vijay is studying in 5th grade. vijay is excellent in sports.vijay like cricket";
String token = "vijay";
StringTokenizer st = new StringTokenizer(s,token);
int count = 0;
while ( st.hasMoreElements() )
{
  String temp = st.nextToken();
  if(count == 0 || count == (st.countTokens() - 1)
  {
    //your code
  }else{
   //your code
  }
 count ++;
}

Upvotes: 0

Jan
Jan

Reputation: 2070

This is a very specific requirement, so the answer is: No, Java does not have any standard function for this.

My recommendation: Use indexOf and lastIndexOf to find the first and the last occurence, split the string, use replaceAll to get rid of all occurences in the middle part, and concatenate everything back together.

If you can't solve this on your own, update the question with your code and your specific question/problem.

Upvotes: 2

Related Questions