You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用三元运算符判断字符串含@且非空后截取子串,否则返回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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 15:42:05