String.StartsWith 方法 (String)

本文介绍 .NET Framework 中 String 类的 StartsWith 方法,该方法用于判断字符串是否以特定字符开始。文章通过示例代码展示了如何使用此方法来移除字符串开头的 HTML 标签。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

.NET Framework 类库 
String.StartsWith 方法 (String) 
请参见  示例

确定此实例的开头是否与指定的字符串匹配。

命名空间:System
程序集:mscorlib(在 mscorlib.dll 中)

语法
C#
public bool StartsWith (
 string value
)
 
 


参数
value
要比较的 String。

 

返回值
如果 value 与此字符串的开头匹配,则为 true;否则为 false。

异常
异常类型 条件
ArgumentNullException
 value 为空引用(在 Visual Basic 中为 Nothing)。
 

备注
此方法将 value 与位于此实例开头、与 value 长度相同的子字符串进行比较,并返回它们是否相等的指示。若要相等,value 必须是空字符串 (Empty)、对此同一实例的引用,或者必须与此实例的开头匹配。

此方法使用当前区域性执行单词(区分大小写和区域性)比较。

示例
下面的代码示例说明了如何使用 StartsWith 方法。

C#  复制代码
using System;

public class EndsWithTest {
    public static void Main() {

        // process a string that contains html tags
        // this sample does not remove embedded tags (tags in the middle of a line)

        string [] strSource = { "<b>This is bold text</b>", "<H1>This is large Text</H1>",
                "<b><i><font color=green>This has multiple tags</font></i></b>",
                "<b>This has <i>embedded</i> tags.</b>",
                "<This line simply begins with a lesser than symbol, it should not be modified" };

        Console.WriteLine("The following lists the items before the tags have been stripped:");
        Console.WriteLine("-----------------------------------------------------------------");

        // print out the initial array of strings
        foreach ( string s in strSource )
            Console.WriteLine( s );

        Console.WriteLine();

        Console.WriteLine("The following lists the items after the tags have been stripped:");
        Console.WriteLine("----------------------------------------------------------------");

        // print out the array of strings
        foreach ( string s in strSource )
            Console.WriteLine( StripStartTags( s ) );
    }

    private static string StripStartTags( string item ) {

        // try to find a tag at the start of the line using StartsWith
        if (item.Trim().StartsWith("<")) {

            // now search for the closing tag...
            int lastLocation = item.IndexOf( ">" );

            // remove the identified section, if it is a valid region
            if ( lastLocation >= 0 )
                item =  item.Substring( lastLocation + 1 );
        }

        return item;
    }
}

 
C++  复制代码
using namespace System;
using namespace System::Collections;
String^ StripStartTags( String^ item )
{
  
   // try to find a tag at the start of the line using StartsWith
   if ( item->Trim()->StartsWith( "<" ) )
   {
     
      // now search for the closing tag->->.
      int lastLocation = item->IndexOf( ">" );
     
      // remove the identified section, if it is a valid region
      if ( lastLocation >= 0 )
            item = item->Substring( lastLocation + 1 );
   }

   return item;
}

int main()
{
  
   // process a string that contains html tags
   // this sample does not remove embedded tags (tags in the middle of a line)
   array<String^>^strSource = {"<b>This is bold text</b>","<H1>This is large Text</H1>","<b><i><font color=green>This has multiple tags</font></i></b>","<b>This has <i>embedded</i> tags.</b>","<This line simply begins with a lesser than symbol, it should not be modified"};
   Console::WriteLine( "The following lists the items before the tags have been stripped:" );
   Console::WriteLine( "-----------------------------------------------------------------" );
  
   // print out the initial array of strings
   IEnumerator^ myEnum1 = strSource->GetEnumerator();
   while ( myEnum1->MoveNext() )
   {
      String^ s = safe_cast<String^>(myEnum1->Current);
      Console::WriteLine( s );
   }

   Console::WriteLine();
   Console::WriteLine( "The following lists the items after the tags have been stripped:" );
   Console::WriteLine( "----------------------------------------------------------------" );
  
   // print [Out] the* array of strings
   IEnumerator^ myEnum2 = strSource->GetEnumerator();
   while ( myEnum2->MoveNext() )
   {
      String^ s = safe_cast<String^>(myEnum2->Current);
      Console::WriteLine( StripStartTags( s ) );
   }
}


 
JScript  复制代码
import System;

public class EndsWithTest {
    public static function Main() : void {

        // process a string that contains html tags
        // this sample does not remove embedded tags (tags in the middle of a line)

        var strSource : String [] = [ "<b>This is bold text</b>", "<H1>This is large Text</H1>",
                "<b><i><font color=green>This has multiple tags</font></i></b>",
                "<b>This has <i>embedded</i> tags.</b>",
                "<This line simply begins with a lesser than symbol, it should not be modified" ];

        Console.WriteLine("The following lists the items before the tags have been stripped:");
        Console.WriteLine("-----------------------------------------------------------------");

        // print out the initial array of strings
        for( var i : int in strSource )
            Console.WriteLine( strSource[i] );

        Console.WriteLine();

        Console.WriteLine("The following lists the items after the tags have been stripped:");
        Console.WriteLine("----------------------------------------------------------------");

        // print out the array of strings
        for ( i in strSource )
            Console.WriteLine( StripStartTags( strSource[i] ) );
    }

    private static function StripStartTags( item : String ) : String  {

        // try to find a tag at the start of the line using StartsWith
        if (item.Trim().StartsWith("<")) {

            // now search for the closing tag...
            var lastLocation : int = item.IndexOf( ">" );

            // remove the identified section, if it is a valid region
            if ( lastLocation >= 0 )
                item =  item.Substring( lastLocation + 1 );
        }

        return item;
    }
}
EndsWithTest.Main();

 

平台
Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求。

版本信息
.NET Framework
受以下版本支持:2.0、1.1、1.0

.NET Compact Framework
受以下版本支持:2.0、1.0

请参见
参考
String 类
String 成员
System 命名空间
EndsWith

### 关于 `String.startsWith` 方法的用法 在 Java 中,`String` 类提供了多种用于字符串操作的方法,其中 `startsWith` 是一种常用的判断方法。该方法用来检测当前字符串是否以指定前缀开头。如果匹配成功,则返回 `true`;否则返回 `false`。 以下是 `startsWith` 的两种重载形式: 1. **`boolean startsWith(String prefix)`**: 判断字符串是否以前缀 `prefix` 开头。 2. **`boolean startsWith(String prefix, int toffset)`**: 从索引位置 `toffset` 开始判断字符串是否以前缀 `prefix` 开头[^3]。 #### 使用示例 下面是一个简单的代码示例展示如何使用 `startsWith` 方法: ```java public class StartsWithExample { public static void main(String[] args) { String str = "HelloWorld"; // 基本用法 boolean result1 = str.startsWith("Hello"); // true System.out.println(result1); // 指定起始位置 boolean result2 = str.startsWith("oW", 4); // true System.out.println(result2); // 不匹配的情况 boolean result3 = str.startsWith("world"); System.out.println(result3); // false } } ``` 需要注意的是,`startsWith` 方法区分大小写。因此,在上面的例子中 `"Hello"` 和 `"hello"` 被视为不同的字符串。 #### 复杂度分析 对于 `startsWith` 方法的时间复杂度通常为 O(n),其中 n 表示要比较的部分长度(即前缀的长度)。这是因为每次调用都需要逐字符对比直到找到不相等的位置或者完成整个前缀的验证为止[^3]。 #### 实际应用场景 此功能常应用于文件路径校验、URL 验证以及日志解析等领域。例如检查某个 URL 是否属于特定域名下的资源链接可以利用这个函数实现快速筛选。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值