**Find another string in a string**

Find another string in a string

public class text{
    
    
	public static void main(String args[]) {
    
    
		String searchMe="Look for a substring in me";
		String subString="sub";
		boolean foundIt=false;
		
		int max=searchMe.length()-subString.length();
		
		test:
			for(int i=0;i<=max;i++) {
    
    
				int n=subString.length();
				int j=i;
				int k=0;
				while(n--!=0) {
    
    
					if(searchMe.charAt(j++)!=subString.charAt(k++)) {
    
    
						continue test;
					}
				}
		        foundIt=true;
		        break test;
			}
		
		System.out.println(foundIt?"Found it":"Didn't find it");
	}
	}

The program is a bit difficult to understand, mainly because of the understanding of the If statement.

if(searchMe.charAt(j++)!=subString.charAt(k++))

This means that from the beginning of finding a structure that is similar to each letter of sub, until a different word appears, it will return to the traversal of the found letter.

For example, looking for subing in 123subsubing, the outer loop is calculated in the order of 123subsubing, 123 passes directly, and then comes to sub. After looping three times in while, the fourth letter does not match, and it starts to match again from u. .

Guess you like

Origin blog.csdn.net/WU_SIMON_SJTU/article/details/109370473