JAvaは、入力した文字列のcount回目の出現時のサブ文字列を別の文字列に置き換えます.

1444 ワード

	//             count                      
	public static String replaceByCount( String inputStr, int sequence,
			String strToFind, String replaceWith ){
		int indexOfTheStr = getFromIndex( inputStr, strToFind, sequence );

		if( indexOfTheStr == -1 ){  //    
			return null;
		}else{
			return inputStr.substring( 0, indexOfTheStr )
					+ replaceWith
					+ inputStr.substring( indexOfTheStr + strToFind.length() );
		}
	}

	//        strToFind      inputStr    count          
	public static int getFromIndex( String inputStr, String strToFind, int count ){
		//         
		java.util.regex.Matcher slashMatcher = java.util.regex.Pattern.compile( strToFind ).matcher( inputStr );

		int index = 0;
		//matcher.find();  //                      

		while( slashMatcher.find() ){
			index++;

			//  strToFind     count       
			if ( index == count ){
				break;
			}
		}

		try{
			// matcher.start();            
			return slashMatcher.start();
		}catch ( Exception e ){
			//e.printStackTrace();

			return -1;   //    
		}
	}

	public static void main(String[] args){
                //       
		String inputStr = "CS1 CS2 CS3 CS4";
		int count = 3;
		String toFind = "CS";
		String replaceWith = "AC";

		//             count                      
		String reStr = replaceByCount( inputStr, count, toFind, replaceWith );
		System.out.println( reStr );   //       CS1 CS2 AC3 CS4
	}