The problem of indexOf and replace in java



The complexity of the two methods is basically the same, but I think the first one may be more flexible, because if the following

field is also of variable length, the reply method cannot be used directly in this way, and it may have to be combined with indexOf. more troublesome.

indexOf method: specifies the position of the first occurrence of the content to be found in the string, and returns -1 if it does not appear, which is case-sensitive. The lastIndexOf method is basically the same, with the following usages:

String str = "hello world" ; /** Find the index of the first occurrence of character 0 */ int a = str.indexOf( "o" ); /** Find the first occurrence of character 0 starting from index 4 position index */ int b = str.indexOf( "o" , 4 ); /** find the position index of the last occurrence of character 0 */ int c = str.lastIndexOf( "o" ); /** find character 0 position index of the last occurrence within index 4 */ int d = str.lastIndexOf( "o" , 4 ); int e = str.lastIndexOf( "o" , 3 ) /** result */ a= 4 ,b = 4 , c= 7 , d= 4 ,e=-1

replace method: replace the corresponding character or string in the string, related methods include replaceFirst and replaceAll. replaceFirst: replace the character or string that appears for the first time in the original string, regardless of the subsequent ones. replaceAll: Compared with replace, it is all replacement. The difference is the replacement based on regular expressions, and the processing of special characters is somewhat different.

Leave a Comment

Your email address will not be published. Required fields are marked *