如何判断3个字符串中恰好仅有1个非空?
校验三个字符串恰好仅有一个非空白的优化实现
我们需要判断三个字符串x、y、z中,是否恰好只有一个字符串不为空白(非空且不是纯空格字符)。你当前的实现逻辑是正确的,但代码冗余度较高、可维护性差,这里提供几种更简洁、易扩展的实现方式:
原实现代码
string x; string y; string z; //Logic here if (!x.IsNullOrWhiteSpace() && y.IsNullOrWhiteSpace() && z.IsNullOrWhiteSpace()) { } else if (x.IsNullOrWhiteSpace() && !y.IsNullOrWhiteSpace() && z.IsNullOrWhiteSpace()) { } else if (x.IsNullOrWhiteSpace() && y.IsNullOrWhiteSpace() && !z.IsNullOrWhiteSpace()) { } else { // 需要处理的不符合条件的场景 }
优化方案1:统计非空白字符串数量
通过统计非空白字符串的总数,判断是否等于1。这种方式扩展性极强,后续新增字符串只需添加到统计集合中即可:
string x; string y; string z; // 基础写法 int nonEmptyCount = 0; if (!string.IsNullOrWhiteSpace(x)) nonEmptyCount++; if (!string.IsNullOrWhiteSpace(y)) nonEmptyCount++; if (!string.IsNullOrWhiteSpace(z)) nonEmptyCount++; if (nonEmptyCount == 1) { // 恰好一个非空白的处理逻辑 } else { // 不符合条件的场景(0个或2个及以上非空白) }
如果项目中引用了System.Linq,可以用更简洁的LINQ写法:
using System.Linq; string x; string y; string z; var nonEmptyCount = new[] { x, y, z }.Count(s => !string.IsNullOrWhiteSpace(s)); if (nonEmptyCount == 1) { // 恰好一个非空白的处理逻辑 } else { // 不符合条件的场景 }
优化方案2:简化分支判断逻辑
若不想用统计或LINQ,也可以通过提取布尔变量来简化分支,减少重复代码:
string x; string y; string z; bool xIsNonEmpty = !string.IsNullOrWhiteSpace(x); bool yIsNonEmpty = !string.IsNullOrWhiteSpace(y); bool zIsNonEmpty = !string.IsNullOrWhiteSpace(z); if ((xIsNonEmpty && !yIsNonEmpty && !zIsNonEmpty) || (!xIsNonEmpty && yIsNonEmpty && !zIsNonEmpty) || (!xIsNonEmpty && !yIsNonEmpty && zIsNonEmpty)) { // 恰好一个非空白的处理逻辑 } else { // 不符合条件的场景 }
内容的提问来源于stack exchange,提问作者Porbst
相关产品推荐
相关产品推荐

