package org.ninjasoft.util;
import java.util.regex.*;
public class NameCopy {
private static final Pattern pattern = Pattern.compile("^.* copy \\d+$");
/**
* Given a name, make a copy like in Windows Explorer. The first copy
* of "ninja" will be "ninja copy". The next will be "ninja copy 1", the
* next will be "ninja copy 2", etc.
* @param source
* @return
*/
public static String copyName(String source) {
// Handle case for "ninja copy"
if (source.endsWith(" copy"))
return source + " 1";
// Handle case for "ninja"
Matcher matcher = pattern.matcher(source);
if (!matcher.matches())
return source + " copy";
// Handle case for "ninja copy 99"
int pos = source.lastIndexOf(' ');
int counter = 0;
try{counter = Text.string2int(source.substring(pos+1));}catch(NumberFormatException e){}
counter++;
return source.substring(0, pos+1) + counter;
}
public static void main(String[] argv) {
String name = "ninja";
for (int i=0; i<20; i++) {
name = copyName(name);
System.out.println(name);
}
}
}