【发布时间】:2020-01-01 02:25:45
【问题描述】:
假设我有很长的字符串,我想查看一列是 allLower、allUpper 还是 mixCase。例如以下列
text
"hello"
"New"
"items"
"iTem12"
"-3nXy"
文本将是mixedCase。确定这一点的简单算法可能是:
int is_mixed_case, is_all_lower, is_all_upper;
int has_lower = 0;
int has_upper = 0;
// for each row...for each column...
for (int i = 0; (c=s[i]) != '\0'; i++) {
if (c >='a' && c <= 'z') {
has_lower = 1;
if (has_upper) break;
}
else if (c >='A' && c <= 'Z') {
has_upper = 1;
if (has_lower) break;
}
}
is_all_lower = has_lower && !has_upper;
is_all_upper = has_upper && !has_lower;
is_mixed_case = has_lower && has_upper;
不过,我确信会有一种更高效的方法来做到这一点。执行此算法/计算的最有效方法可能是什么?
【问题讨论】:
-
只要你在每种情况下找到一个字符,它就会混合大小写,总共可能只有两个字符。所以如果你遍历整个字符串,你可能会浪费很多时间。
-
@jonrsharpe -- 谢谢你的建议,我已经更新了它。
-
获取第一个字符的大小写。然后使用
strspn()搜索相反情况下的字符。 -
另外...我们在说什么character set?使用 Unicode 时,事情变得非常棘手...... ;)
标签: c string algorithm optimization