如何检查其中存在的特定字符

问题描述 投票:0回答:1

这是我的代码:

using System;

namespace HelloWorld
{
    class Program
    {  
        static void Main(string[] args)
        {
            string ContactEmail = "[email protected]";
            Console.WriteLine("Hello World!"); 
      
            Console.WriteLine(ContactEmail.Substring(0, ContactEmail.IndexOf('@'))); 
        }
    }
}

输出:小指。

我想检查字符串是否包含

@
并且不为空,然后只查找子字符串,否则返回
null
。不需要 If else 块。在同一行中使用
:
运算符

c# linq
1个回答
0
投票

好吧,您可以在

index
的帮助下找到
IndexOf
,然后检查
index
是否有
-1
- 如果未找到
@

int index = ContactEmail.IndexOf('@');

// If you don't want "if" let's use ternary operator
var result = index < 0 ? null : ContactEmail[0..index];
© www.soinside.com 2019 - 2024. All rights reserved.