我希望了解如何使用两个字符串生成唯一标识符,这与IT技术有关。我的要求是为特定文档生成唯一标识符。为了生成id,必须使用文档的“名称”和“版本”。同时,应该有一种方法从特定文档的唯一标识符中获取“名称”和“版本”。在Java中,是否可以使用UUID来实现这一点?或者有没有更好的方法。我们可以使用哈希或编码来实现这个目的吗?如果可以,怎么做?
我不知道为什么您想要使用两个字符串来生成唯一标识符,并且在某些情况下可能无法保持唯一性。 java.util.UUID
提供了适合您情况的有用方法。看一下以下示例的用法:
import java.util.UUID;
...
UUID idOne = UUID.randomUUID();
UUID idTwo = UUID.randomUUID();
如果您不想创建UUID,只需保持纯字符串
String.format("%s_%s_%s_%s", str1.length(), str2.length(), str1, str2);
使用以下进行测试
Pair.of("a", ""), // 'a' and '' into '1_0_a_'
Pair.of("", "a"), // '' and 'a' into '0_1__a'
Pair.of("a", "a"), // 'a' and 'a' into '1_1_a_a'
Pair.of("aa", "a"), // 'aa' and 'a' into '2_1_aa_a'
Pair.of("a", "aa"), // 'a' and 'aa' into '1_2_a_aa'
Pair.of("_", ""), // '_' and '' into '1_0___'
Pair.of("", "_"), // '' and '_' into '0_1___'
Pair.of("__", "_"), // '__' and '_' into '2_1_____'
Pair.of("_", "__"), // '_' and '__' into '1_2_____'
Pair.of("__", "__"), // '__' and '__' into '2_2______'
Pair.of("/t/", "/t/"), // '/t/' and '/t/' into '3_3_/t/_/t/'
Pair.of("", "") // '' and '' into '0_0__'
这个方法有效是因为它创建了一种使用不能与数字共存的分隔符来解析后续内容的方式,如果使用像“0”这样的分隔符,则会失败。
其他示例依赖于两个字符串中都不存在该分隔符。
str1+"."+str2
// both "..","." and ".",".." result in "...."
编辑
支持合并“n”个字符串
private static String getUniqueString(String...srcs) {
StringBuilder uniqueCombo = new StringBuilder();
for (String src : srcs) {
uniqueCombo.append(src.length());
uniqueCombo.append('_');
}
// adding this second _ between numbers and strings allows unique strings across sizes
uniqueCombo.append('_');
for (String src : srcs) {
uniqueCombo.append(src);
uniqueCombo.append('_');
}
return uniqueCombo.toString();
}
void main() {
print(join('String1', 'String2'));
print(join('String2', 'String1'));
print(join('Hello', 'World'));
print(join('World', 'Hello'));
}
String join (String str1, String str2) {
String result = '';
if (str1.hashCode <= str2.hashCode) {
result = '$str1-$str2';
} else {
result = '$str2-$str1';
}
return result;
}
与上面的代码相同,您可以对字符串进行排序,然后执行任何操作以获得唯一键。
最好的方法是使用一个在这些字符串中通常不会出现的分隔符来连接字符串
例如:
String name = ....
String version = .....
String key = name + "/" + version;
你可以使用 split("/")
来获取原始名称和版本号。
您可以使用静态工厂方法randomUUID()
来获取一个UUID
对象:
UUID id = UUID.randomUUID();
为了将ID与版本号组合起来,可以想出一个分隔符,确保该分隔符不会出现在任何一个字符串中,例如/
或_
。然后,您可以使用该分隔符进行split
操作,或使用正则表达式提取所需内容:
String entry = id + "_" + version;
String[] divided = entry.split(delimiter);
//or using regex
String entry= "idName_version"; //delimiter is "_"
String pattern = "(.*)_(.*)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(example);
if (m.find())
{
System.out.println(m.group(1)); //prints idName
System.out.println(m.group(2)); //prints version
}