如何用三元运算符判断字符串含@且非空后截取子串,否则返回null
用三元运算符实现邮箱前缀截取逻辑
原代码
using System; namespace HelloWorld { class Program { static void Main(string[] args) { string ContactEmail = "pinky@gmail.com"; Console.WriteLine("Hello World!"); Console.WriteLine(ContactEmail.Substring(0, ContactEmail.IndexOf('@'))); } } }
原代码输出:pinky
需求说明
需要实现以下逻辑:
- 判断目标字符串非空且包含@符号
- 满足条件时,截取@符号之前的子串
- 不满足条件时返回
null - 要求仅用三元运算符一行实现,禁止使用
if else语句
解决方案代码
using System; namespace HelloWorld { class Program { static void Main(string[] args) { string ContactEmail = "pinky@gmail.com"; Console.WriteLine("Hello World!"); // 一行实现逻辑 string result = !string.IsNullOrEmpty(ContactEmail) && ContactEmail.Contains('@') ? ContactEmail.Substring(0, ContactEmail.IndexOf('@')) : null; Console.WriteLine(result); // 输出: pinky } } }
逻辑说明
- 用
!string.IsNullOrEmpty(ContactEmail)确保字符串不为空或null - 用
ContactEmail.Contains('@')检查字符串包含@符号 - 两个条件通过
&&关联,必须同时满足才执行截取操作 - 三元运算符
?:直接完成分支判断,无需if else
边界情况补充(可选)
如果需要排除@在字符串开头的情况(比如@example.com),可以在条件中追加ContactEmail.IndexOf('@') > 0,修改后的判断逻辑如下:
string result = !string.IsNullOrEmpty(ContactEmail) && ContactEmail.Contains('@') && ContactEmail.IndexOf('@') > 0 ? ContactEmail.Substring(0, ContactEmail.IndexOf('@')) : null;
内容的提问来源于stack exchange,提问作者Pinky
相关产品推荐
相关产品推荐

