c#中的左函数

42 c# string

可能重复:
.Net相当于旧的vb left(字符串,长度)函数?

在c#中左手功能的替代方案是什么呢?

Left(fac.GetCachedValue("Auto Print Clinical Warnings").ToLower + " ", 1) == "y");
Run Code Online (Sandbox Code Playgroud)

jas*_*son 120

听起来你问的是一个功能

string Left(string s, int left)
Run Code Online (Sandbox Code Playgroud)

这将返回left字符串最左边的字符s.在这种情况下,你可以使用String.Substring.您可以将其写为扩展方法:

public static class StringExtensions
{
    public static string Left(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value)) return value;
        maxLength = Math.Abs(maxLength);

        return ( value.Length <= maxLength 
               ? value 
               : value.Substring(0, maxLength)
               );
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

string left = s.Left(number);
Run Code Online (Sandbox Code Playgroud)

对于您的具体示例:

string s = fac.GetCachedValue("Auto Print Clinical Warnings").ToLower() + " ";
string left = s.Substring(0, 1);
Run Code Online (Sandbox Code Playgroud)

  • 编辑通过null,空和短于所需的字符串不变. (3认同)

Pet*_* O. 55

它是Substring方法String,第一个参数设置为0.

 myString.Substring(0,1);
Run Code Online (Sandbox Code Playgroud)

[以下是Almo添加的; 请参阅Justin J Stark的评论.-Peter O.]

警告:如果字符串的长度小于您正在使用的字符数,您将得到一个ArgumentOutOfRangeException.

  • 小心:如果字符串的长度小于你正在使用的字符数,你将得到一个ArgumentOutOfRangeException. (11认同)
  • 我使用Math.Min来避免ArgumentOutOfRangeException:myString.Substring(0,Math.Min(numberOfCharacters,myString.Length)) (6认同)

Rol*_*lig 11

只要写下你真正想知道的东西:

fac.GetCachedValue("Auto Print Clinical Warnings").ToLower().StartsWith("y")
Run Code Online (Sandbox Code Playgroud)

它比带子串的任何东西都简单得多.


Dav*_*ras 7

使用substring函数:

yourString.Substring(0, length);
Run Code Online (Sandbox Code Playgroud)

  • 小心:如果字符串的长度小于你正在使用的字符数,你将得到一个ArgumentOutOfRangeException. (5认同)