我有一个方法获取两个字符串。这些字符串可以同时包含数字,ASCII字符或两者。比较数值作为字符串
的算法是这样的:
- 拆分两个字符串转换成char数组A和B.
- 尝试解析元素A 我和B 我为int
- 比较元素A i带元素B i,在整数使用直接比较的情况下,在字符使用序数字符串比较的情况下。
- 根据结果
现在做的工作,我想知道:我真的需要解析的元素为int?我只是可以比较序号字符串比较中的每个元素,并得到相同的结果,对吧? 这里的性能影响是什么?解析和正常比较比序列字符串比较更快吗?它慢吗?
是我的假设(使用序数字符串比较而不是解析和比较)是否正确?
这里是有问题的方法:
internal static int CompareComponentString(this string componentString, string other)
{
bool componentEmpty = string.IsNullOrWhiteSpace(componentString);
bool otherEmtpy = string.IsNullOrWhiteSpace(other);
if (componentEmpty && otherEmtpy)
{
return 0;
}
if (componentEmpty)
{
return -1;
}
if (otherEmtpy)
{
return 1;
}
string[] componentParts = componentString.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
string[] otherParts = other.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < Math.Min(componentParts.Length, otherParts.Length); i++)
{
string componentChar = componentParts[i];
string otherChar = otherParts[i];
int componentNumVal, otherNumVal;
bool componentIsNum = int.TryParse(componentChar, out componentNumVal);
bool otherIsNum = int.TryParse(otherChar, out otherNumVal);
if (componentIsNum && otherIsNum)
{
if (componentNumVal.CompareTo(otherNumVal) == 0)
{
continue;
}
return componentNumVal.CompareTo(otherNumVal);
}
else
{
if (componentIsNum)
{
return -1;
}
if (otherIsNum)
{
return 1;
}
int comp = string.Compare(componentChar, otherChar, StringComparison.OrdinalIgnoreCase);
if (comp != 0)
{
return comp;
}
}
}
return componentParts.Length.CompareTo(otherParts.Length);
}
这是可能被使用的字符串。在使用减号后,我可能只添加部分。
- 1.0.0-α
- 1.0.0-alpha.1
- 1.0.0-alpha.beta
- 1.0.0-beta.2
如果你能给出一些你的字符串的例子,对我们来说会更容易。 – wimh
如果您只比较一个数字,则字符串比较会给出与解析和执行整数比较相同的结果。但是,您还应该考虑是否有可能将数字与ASCII进行比较的情况,如果是,应该发生什么情况。 –
我添加了我目前使用的代码 – Ruhrpottpatriot