String.StartsWith Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Перегрузки
| Имя | Описание |
|---|---|
| StartsWith(Char) |
Определяет, начинается ли этот экземпляр строки с указанным символом. |
| StartsWith(String) |
Определяет, соответствует ли начало данного экземпляра строки указанной строке. |
| StartsWith(Rune) | |
| StartsWith(Char, StringComparison) | |
| StartsWith(String, StringComparison) |
Определяет, соответствует ли начало этого экземпляра строки указанной строке при сравнении с помощью указанного параметра сравнения. |
| StartsWith(Rune, StringComparison) | |
| StartsWith(String, Boolean, CultureInfo) |
Определяет, соответствует ли начало этого экземпляра строки указанной строке при сравнении с указанным языком и региональными параметрами. |
StartsWith(Char)
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
Определяет, начинается ли этот экземпляр строки с указанным символом.
public:
bool StartsWith(char value);
public bool StartsWith(char value);
member this.StartsWith : char -> bool
Public Function StartsWith (value As Char) As Boolean
Параметры
- value
- Char
Символ для сравнения.
Возвращаемое значение
trueЗначение , valueесли false соответствует началу этой строки; в противном случае .
Комментарии
Этот метод выполняет порядковое сравнение (учитывает регистр и не учитывает язык и региональные параметры).
Применяется к
StartsWith(String)
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
Определяет, соответствует ли начало данного экземпляра строки указанной строке.
public:
bool StartsWith(System::String ^ value);
public bool StartsWith(string value);
member this.StartsWith : string -> bool
Public Function StartsWith (value As String) As Boolean
Параметры
- value
- String
Строка для сравнения.
Возвращаемое значение
trueЗначение , valueесли false соответствует началу этой строки; в противном случае .
Исключения
value равно null.
Примеры
В следующем примере определяется StripStartTags метод, использующий StartsWith(String) метод для удаления тегов запуска HTML с начала строки. Обратите внимание, что метод вызывается рекурсивно, чтобы убедиться, что StripStartTags несколько тегов запуска HTML в начале строки удаляются. В этом примере не удаляются html-теги, внедренные в строку.
using System;
public class Example
{
public static void Main() {
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" };
// Display the initial string array.
Console.WriteLine("The original strings:");
Console.WriteLine("---------------------");
foreach (var s in strSource)
Console.WriteLine(s);
Console.WriteLine();
Console.WriteLine("Strings after starting tags have been stripped:");
Console.WriteLine("-----------------------------------------------");
// Display the strings with starting tags removed.
foreach (var s in strSource)
Console.WriteLine(StripStartTags(s));
}
private static string StripStartTags(string item)
{
// Determine whether a tag begins the string.
if (item.Trim().StartsWith("<")) {
// Find the closing tag.
int lastLocation = item.IndexOf( ">" );
// Remove the tag.
if (lastLocation >= 0) {
item = item.Substring( lastLocation + 1 );
// Remove any additional starting tags.
item = StripStartTags(item);
}
}
return item;
}
}
// The example displays the following output:
// The original strings:
// ---------------------
// <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
//
// Strings after starting tags have been stripped:
// -----------------------------------------------
// This is bold text</b>
// This is large Text</H1>
// This has multiple tags</font></i></b>
// This has <i>embedded</i> tags.</b>
// <This line simply begins with a lesser than symbol, it should not be modified
let rec stripStartTags (item: string) =
// Determine whether a tag begins the string.
if item.Trim().StartsWith "<" then
// Find the closing tag.
let lastLocation = item.IndexOf ">"
// Remove the tag.
let item =
if lastLocation >= 0 then
item.Substring( lastLocation + 1 )
else
item
// Remove any additional starting tags.
stripStartTags item
else
item
let 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" |]
// Display the initial string array.
printfn "The original strings:"
printfn "---------------------"
for s in strSource do
printfn $"{s}"
printfn ""
printfn "Strings after starting tags have been stripped:"
printfn "-----------------------------------------------"
// Display the strings with starting tags removed.
for s in strSource do
printfn $"{stripStartTags s}"
// The example displays the following output:
// The original strings:
// ---------------------
// <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
//
// Strings after starting tags have been stripped:
// -----------------------------------------------
// This is bold text</b>
// This is large Text</H1>
// This has multiple tags</font></i></b>
// This has <i>embedded</i> tags.</b>
// <This line simply begins with a lesser than symbol, it should not be modified
Public Class Example
Public Shared Sub Main()
Dim strSource() As 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" }
' Display the initial string array.
Console.WriteLine("The original strings:")
Console.WriteLine("---------------------")
For Each s In strSource
Console.WriteLine(s)
Next
Console.WriteLine()
Console.WriteLine("Strings after starting tags have been stripped:")
Console.WriteLine("-----------------------------------------------")
' Display the strings with starting tags removed.
For Each s In strSource
Console.WriteLine(StripStartTags(s))
Next
End Sub
Private Shared Function StripStartTags(item As String) As String
' Determine whether a tag begins the string.
If item.Trim().StartsWith("<") Then
' Find the closing tag.
Dim lastLocation As Integer = item.IndexOf(">")
If lastLocation >= 0 Then
' Remove the tag.
item = item.Substring((lastLocation + 1))
' Remove any additional starting tags.
item = StripStartTags(item)
End If
End If
Return item
End Function
End Class
' The example displays the following output:
' The original strings:
' ---------------------
' <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
'
' Strings after starting tags have been stripped:
' -----------------------------------------------
' This is bold text</b>
' This is large Text</H1>
' This has multiple tags</font></i></b>
' This has <i>embedded</i> tags.</b>
' <This line simply begins with a lesser than symbol, it should not be modified
Комментарии
Этот метод сравнивает value подстроку в начале этого экземпляра с той же длиной, что valueи значение, указывающее, равны ли они. Чтобы быть равным, value должен быть пустой строкой (String.Empty), должен быть ссылкой на этот же экземпляр или должен соответствовать началу этого экземпляра.
Этот метод выполняет сравнение слов (с учетом регистра и языка и региональных параметров) с помощью текущего языка и региональных параметров.
Примечания для тех, кто вызывает этот метод
Как описано в рекомендациях по использованию строк, рекомендуется избегать вызова методов сравнения строк, заменяющих значения по умолчанию и вызывающих методы, требующие явного указания параметров. Чтобы определить, начинается ли строка с определенной подстроки с помощью правил сравнения строк текущего языка и региональных параметров, явно сообщите о намерении путем вызова StartsWith(String, StringComparison) перегрузки метода со значением CurrentCulture для его comparisonType параметра. Если вам не требуется лингвистическое сравнение, рассмотрите возможность использования Ordinal.
См. также раздел
Применяется к
StartsWith(Rune)
- Исходный код:
- String.Comparison.cs
public:
bool StartsWith(System::Text::Rune value);
public bool StartsWith(System.Text.Rune value);
member this.StartsWith : System.Text.Rune -> bool
Public Function StartsWith (value As Rune) As Boolean
Параметры
- value
- Rune
Возвращаемое значение
Применяется к
StartsWith(Char, StringComparison)
- Исходный код:
- String.Comparison.cs
public:
bool StartsWith(char value, StringComparison comparisonType);
public bool StartsWith(char value, StringComparison comparisonType);
member this.StartsWith : char * StringComparison -> bool
Public Function StartsWith (value As Char, comparisonType As StringComparison) As Boolean
Параметры
- value
- Char
- comparisonType
- StringComparison
Возвращаемое значение
Применяется к
StartsWith(String, StringComparison)
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
Определяет, соответствует ли начало этого экземпляра строки указанной строке при сравнении с помощью указанного параметра сравнения.
public:
bool StartsWith(System::String ^ value, StringComparison comparisonType);
public bool StartsWith(string value, StringComparison comparisonType);
[System.Runtime.InteropServices.ComVisible(false)]
public bool StartsWith(string value, StringComparison comparisonType);
member this.StartsWith : string * StringComparison -> bool
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.StartsWith : string * StringComparison -> bool
Public Function StartsWith (value As String, comparisonType As StringComparison) As Boolean
Параметры
- value
- String
Строка для сравнения.
- comparisonType
- StringComparison
Одно из значений перечисления, определяющее, как эта строка и value сравниваются.
Возвращаемое значение
trueЗначение , valueесли этот экземпляр начинается сfalse; в противном случае .
- Атрибуты
Исключения
value равно null.
comparisonType значение не является значением StringComparison .
Примеры
В следующем примере выполняется поиск строки "the" в начале длинной строки, начинающейся с слова "The". Как показано в выходных данных примера, вызов метода, выполняющего нечувствительный язык и региональные параметры, но сравнение с учетом регистра не соответствует строке, в то время как вызов StartsWith(String, StringComparison) , выполняющий сравнение языка и региональных параметров и регистра, соответствует строке.
using System;
public class Example
{
public static void Main()
{
String title = "The House of the Seven Gables";
String searchString = "the";
StringComparison comparison = StringComparison.InvariantCulture;
Console.WriteLine("'{0}':", title);
Console.WriteLine(" Starts with '{0}' ({1:G} comparison): {2}",
searchString, comparison,
title.StartsWith(searchString, comparison));
comparison = StringComparison.InvariantCultureIgnoreCase;
Console.WriteLine(" Starts with '{0}' ({1:G} comparison): {2}",
searchString, comparison,
title.StartsWith(searchString, comparison));
}
}
// The example displays the following output:
// 'The House of the Seven Gables':
// Starts with 'the' (InvariantCulture comparison): False
// Starts with 'the' (InvariantCultureIgnoreCase comparison): True
open System
let title = "The House of the Seven Gables"
let searchString = "the"
let comparison = StringComparison.InvariantCulture
printfn $"'{title}':"
printfn $" Starts with '{searchString}' ({comparison:G} comparison): {title.StartsWith(searchString, comparison)}"
let comparison2 = StringComparison.InvariantCultureIgnoreCase
printfn $" Starts with '{searchString}' ({comparison2:G} comparison): {title.StartsWith(searchString, comparison2)}"
// The example displays the following output:
// 'The House of the Seven Gables':
// Starts with 'the' (InvariantCulture comparison): False
// Starts with 'the' (InvariantCultureIgnoreCase comparison): True
Module Example
Public Sub Main()
Dim title As String = "The House of the Seven Gables"
Dim searchString As String = "the"
Dim comparison As StringComparison = StringComparison.InvariantCulture
Console.WriteLine("'{0}':", title)
Console.WriteLine(" Starts with '{0}' ({1:G} comparison): {2}",
searchString, comparison,
title.StartsWith(searchString, comparison))
comparison = StringComparison.InvariantCultureIgnoreCase
Console.WriteLine(" Starts with '{0}' ({1:G} comparison): {2}",
searchString, comparison,
title.StartsWith(searchString, comparison))
End Sub
End Module
' The example displays the following output:
' 'The House of the Seven Gables':
' Starts with 'the' (InvariantCulture comparison): False
' Starts with 'the' (InvariantCultureIgnoreCase comparison): True
В следующем примере определяется, начинается ли строка с определенной подстроки. Он инициализирует двухмерный массив строк. Первый элемент во втором измерении содержит строку, а второй элемент содержит строку для поиска в начале первой строки. Результаты влияют на выбор языка и региональных параметров, независимо от того, игнорируется ли случай и выполняется ли порядковое сравнение. Обратите внимание, что если экземпляр строки содержит лигатуру, с учетом языка и региональных параметров сравнения со своими последовательными символами успешно совпадают.
using System;
public class Example
{
public static void Main()
{
string[,] strings = { {"ABCdef", "abc" },
{"ABCdef", "abc" },
{"œil","oe" },
{ "læring}", "lae" } };
for (int ctr1 = strings.GetLowerBound(0); ctr1 <= strings.GetUpperBound(0); ctr1++)
{
foreach (string cmpName in Enum.GetNames(typeof(StringComparison)))
{
StringComparison strCmp = (StringComparison) Enum.Parse(typeof(StringComparison),
cmpName);
string instance = strings[ctr1, 0];
string value = strings[ctr1, 1];
Console.WriteLine("{0} starts with {1}: {2} ({3} comparison)",
instance, value,
instance.StartsWith(value, strCmp),
strCmp);
}
Console.WriteLine();
}
}
}
// The example displays the following output:
// ABCdef starts with abc: False (CurrentCulture comparison)
// ABCdef starts with abc: True (CurrentCultureIgnoreCase comparison)
// ABCdef starts with abc: False (InvariantCulture comparison)
// ABCdef starts with abc: True (InvariantCultureIgnoreCase comparison)
// ABCdef starts with abc: False (Ordinal comparison)
// ABCdef starts with abc: True (OrdinalIgnoreCase comparison)
//
// ABCdef starts with abc: False (CurrentCulture comparison)
// ABCdef starts with abc: True (CurrentCultureIgnoreCase comparison)
// ABCdef starts with abc: False (InvariantCulture comparison)
// ABCdef starts with abc: True (InvariantCultureIgnoreCase comparison)
// ABCdef starts with abc: False (Ordinal comparison)
// ABCdef starts with abc: True (OrdinalIgnoreCase comparison)
//
// œil starts with oe: True (CurrentCulture comparison)
// œil starts with oe: True (CurrentCultureIgnoreCase comparison)
// œil starts with oe: True (InvariantCulture comparison)
// œil starts with oe: True (InvariantCultureIgnoreCase comparison)
// œil starts with oe: False (Ordinal comparison)
// œil starts with oe: False (OrdinalIgnoreCase comparison)
//
// læring} starts with lae: True (CurrentCulture comparison)
// læring} starts with lae: True (CurrentCultureIgnoreCase comparison)
// læring} starts with lae: True (InvariantCulture comparison)
// læring} starts with lae: True (InvariantCultureIgnoreCase comparison)
// læring} starts with lae: False (Ordinal comparison)
// læring} starts with lae: False (OrdinalIgnoreCase comparison)
open System
let strings =
array2D
[ [ "ABCdef"; "abc" ]
[ "ABCdef"; "abc" ]
[ "œil"; "oe" ]
[ "læring}"; "lae" ] ]
for ctr1 = strings.GetLowerBound 0 to strings.GetUpperBound 0 do
for cmpName in Enum.GetNames typeof<StringComparison> do
let strCmp = Enum.Parse(typeof<StringComparison>, cmpName) :?> StringComparison
let instance = strings[ctr1, 0]
let value = strings[ctr1, 1]
printfn $"{instance} starts with {value}: {instance.StartsWith(value, strCmp)} ({strCmp} comparison)"
printfn ""
// The example displays the following output:
// ABCdef starts with abc: False (CurrentCulture comparison)
// ABCdef starts with abc: True (CurrentCultureIgnoreCase comparison)
// ABCdef starts with abc: False (InvariantCulture comparison)
// ABCdef starts with abc: True (InvariantCultureIgnoreCase comparison)
// ABCdef starts with abc: False (Ordinal comparison)
// ABCdef starts with abc: True (OrdinalIgnoreCase comparison)
//
// ABCdef starts with abc: False (CurrentCulture comparison)
// ABCdef starts with abc: True (CurrentCultureIgnoreCase comparison)
// ABCdef starts with abc: False (InvariantCulture comparison)
// ABCdef starts with abc: True (InvariantCultureIgnoreCase comparison)
// ABCdef starts with abc: False (Ordinal comparison)
// ABCdef starts with abc: True (OrdinalIgnoreCase comparison)
//
// œil starts with oe: True (CurrentCulture comparison)
// œil starts with oe: True (CurrentCultureIgnoreCase comparison)
// œil starts with oe: True (InvariantCulture comparison)
// œil starts with oe: True (InvariantCultureIgnoreCase comparison)
// œil starts with oe: False (Ordinal comparison)
// œil starts with oe: False (OrdinalIgnoreCase comparison)
//
// læring} starts with lae: True (CurrentCulture comparison)
// læring} starts with lae: True (CurrentCultureIgnoreCase comparison)
// læring} starts with lae: True (InvariantCulture comparison)
// læring} starts with lae: True (InvariantCultureIgnoreCase comparison)
// læring} starts with lae: False (Ordinal comparison)
// læring} starts with lae: False (OrdinalIgnoreCase comparison)
Module Example
Public Sub Main()
Dim strings(,) As String = { {"ABCdef", "abc" },
{"ABCdef", "abc" },
{"œil","oe" },
{ "læring}", "lae" } }
For ctr1 As Integer = strings.GetLowerBound(0) To strings.GetUpperBound(0)
For Each cmpName As String In [Enum].GetNames(GetType(StringComparison))
Dim strCmp As StringComparison = CType([Enum].Parse(GetType(StringComparison),
cmpName), StringComparison)
Dim instance As String = strings(ctr1, 0)
Dim value As String = strings(ctr1, 1)
Console.WriteLine("{0} starts with {1}: {2} ({3} comparison)",
instance, value,
instance.StartsWith(value, strCmp),
strCmp)
Next
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' ABCdef starts with abc: False (CurrentCulture comparison)
' ABCdef starts with abc: True (CurrentCultureIgnoreCase comparison)
' ABCdef starts with abc: False (InvariantCulture comparison)
' ABCdef starts with abc: True (InvariantCultureIgnoreCase comparison)
' ABCdef starts with abc: False (Ordinal comparison)
' ABCdef starts with abc: True (OrdinalIgnoreCase comparison)
'
' ABCdef starts with abc: False (CurrentCulture comparison)
' ABCdef starts with abc: True (CurrentCultureIgnoreCase comparison)
' ABCdef starts with abc: False (InvariantCulture comparison)
' ABCdef starts with abc: True (InvariantCultureIgnoreCase comparison)
' ABCdef starts with abc: False (Ordinal comparison)
' ABCdef starts with abc: True (OrdinalIgnoreCase comparison)
'
' œil starts with oe: True (CurrentCulture comparison)
' œil starts with oe: True (CurrentCultureIgnoreCase comparison)
' œil starts with oe: True (InvariantCulture comparison)
' œil starts with oe: True (InvariantCultureIgnoreCase comparison)
' œil starts with oe: False (Ordinal comparison)
' œil starts with oe: False (OrdinalIgnoreCase comparison)
'
' læring} starts with lae: True (CurrentCulture comparison)
' læring} starts with lae: True (CurrentCultureIgnoreCase comparison)
' læring} starts with lae: True (InvariantCulture comparison)
' læring} starts with lae: True (InvariantCultureIgnoreCase comparison)
' læring} starts with lae: False (Ordinal comparison)
' læring} starts with lae: False (OrdinalIgnoreCase comparison)
Комментарии
Метод StartsWith сравнивает value параметр с подстрокой в начале этой строки и возвращает значение, указывающее, равны ли они. Чтобы быть равным, должен быть ссылкой на эту же строку, value должен быть пустой строкой (""), или должен соответствовать началу этой строки. Тип сравнения, выполняемого методом StartsWith , зависит от значения comparisonType параметра. Сравнение может использовать соглашения текущего языка и региональных параметров (StringComparison.CurrentCulture и) или StringComparison.CurrentCultureIgnoreCaseинвариантного языка и региональных параметров (StringComparison.InvariantCulture и StringComparison.InvariantCultureIgnoreCase), либо может состоять из сравнения кодовых точек (StringComparison.Ordinal или StringComparison.OrdinalIgnoreCase). Сравнение также может быть чувствительным к регистру (StringComparison.CurrentCulture, StringComparison.InvariantCultureилиStringComparison.Ordinal) или может игнорировать регистр (StringComparison.CurrentCultureIgnoreCase, , StringComparison.InvariantCultureIgnoreCase). StringComparison.OrdinalIgnoreCase
См. также раздел
Применяется к
StartsWith(Rune, StringComparison)
- Исходный код:
- String.Comparison.cs
public:
bool StartsWith(System::Text::Rune value, StringComparison comparisonType);
public bool StartsWith(System.Text.Rune value, StringComparison comparisonType);
member this.StartsWith : System.Text.Rune * StringComparison -> bool
Public Function StartsWith (value As Rune, comparisonType As StringComparison) As Boolean
Параметры
- value
- Rune
- comparisonType
- StringComparison
Возвращаемое значение
Применяется к
StartsWith(String, Boolean, CultureInfo)
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
- Исходный код:
- String.Comparison.cs
Определяет, соответствует ли начало этого экземпляра строки указанной строке при сравнении с указанным языком и региональными параметрами.
public:
bool StartsWith(System::String ^ value, bool ignoreCase, System::Globalization::CultureInfo ^ culture);
public bool StartsWith(string value, bool ignoreCase, System.Globalization.CultureInfo? culture);
public bool StartsWith(string value, bool ignoreCase, System.Globalization.CultureInfo culture);
member this.StartsWith : string * bool * System.Globalization.CultureInfo -> bool
Public Function StartsWith (value As String, ignoreCase As Boolean, culture As CultureInfo) As Boolean
Параметры
- value
- String
Строка для сравнения.
- ignoreCase
- Boolean
true Значение , чтобы игнорировать регистр во время сравнения; falseв противном случае .
- culture
- CultureInfo
Культурные сведения, определяющие, как эта строка и value сравниваются. Если culture является null, используется текущая культура.
Возвращаемое значение
true
value Значение , falseесли параметр соответствует началу этой строки; в противном случае .
Исключения
value равно null.
Примеры
В следующем примере определяется, возникает ли строка в начале другой строки. Метод StartsWith вызывается несколько раз с использованием конфиденциальности регистра, нечувствительности регистра и различных региональных параметров, влияющих на результаты поиска.
// This code example demonstrates the
// System.String.StartsWith(String, ..., CultureInfo) method.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string msg1 = "Search for the target string \"{0}\" in the string \"{1}\".\n";
string msg2 = "Using the {0} - \"{1}\" culture:";
string msg3 = " The string to search ends with the target string: {0}";
bool result = false;
CultureInfo ci;
// Define a target string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string capitalARing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string aRingXYZ = "\u0061\u030a" + "xyz";
// Clear the screen and display an introduction.
Console.Clear();
// Display the string to search for and the string to search.
Console.WriteLine(msg1, capitalARing, aRingXYZ);
// Search using English-United States culture.
ci = new CultureInfo("en-US");
Console.WriteLine(msg2, ci.DisplayName, ci.Name);
Console.WriteLine("Case sensitive:");
result = aRingXYZ.StartsWith(capitalARing, false, ci);
Console.WriteLine(msg3, result);
Console.WriteLine("Case insensitive:");
result = aRingXYZ.StartsWith(capitalARing, true, ci);
Console.WriteLine(msg3, result);
Console.WriteLine();
// Search using Swedish-Sweden culture.
ci = new CultureInfo("sv-SE");
Console.WriteLine(msg2, ci.DisplayName, ci.Name);
Console.WriteLine("Case sensitive:");
result = aRingXYZ.StartsWith(capitalARing, false, ci);
Console.WriteLine(msg3, result);
Console.WriteLine("Case insensitive:");
result = aRingXYZ.StartsWith(capitalARing, true, ci);
Console.WriteLine(msg3, result);
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
Search for the target string "Å" in the string "a°xyz".
Using the English (United States) - "en-US" culture:
Case sensitive:
The string to search ends with the target string: False
Case insensitive:
The string to search ends with the target string: True
Using the Swedish (Sweden) - "sv-SE" culture:
Case sensitive:
The string to search ends with the target string: False
Case insensitive:
The string to search ends with the target string: False
*/
// This code example demonstrates the
// System.String.StartsWith(String, ..., CultureInfo) method.
open System
open System.Globalization
[<EntryPoint>]
let main _ =
let msg1 = "Search for the target string \"{0}\" in the string \"{1}\".\n"
let msg2 = "Using the {0} - \"{1}\" culture:"
let msg3 = " The string to search ends with the target string: {0}"
// Define a target string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let capitalARing = "\u00c5"
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let aRingXYZ = "\u0061\u030a" + "xyz"
// Clear the screen and display an introduction.
Console.Clear()
// Display the string to search for and the string to search.
Console.WriteLine(msg1, capitalARing, aRingXYZ)
// Search using English-United States culture.
let ci = CultureInfo "en-US"
Console.WriteLine(msg2, ci.DisplayName, ci.Name)
printfn "Case sensitive:"
let result = aRingXYZ.StartsWith(capitalARing, false, ci)
Console.WriteLine(msg3, result)
printfn "Case insensitive:"
let result = aRingXYZ.StartsWith(capitalARing, true, ci)
Console.WriteLine(msg3, result)
printfn ""
// Search using Swedish-Sweden culture.
let ci = CultureInfo "sv-SE"
Console.WriteLine(msg2, ci.DisplayName, ci.Name)
printfn "Case sensitive:"
let result = aRingXYZ.StartsWith(capitalARing, false, ci)
Console.WriteLine(msg3, result)
printfn "Case insensitive:"
let result = aRingXYZ.StartsWith(capitalARing, true, ci)
Console.WriteLine(msg3, result)
0
(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
Search for the target string "Å" in the string "a°xyz".
Using the English (United States) - "en-US" culture:
Case sensitive:
The string to search ends with the target string: False
Case insensitive:
The string to search ends with the target string: True
Using the Swedish (Sweden) - "sv-SE" culture:
Case sensitive:
The string to search ends with the target string: False
Case insensitive:
The string to search ends with the target string: False
*)
' This code example demonstrates the
' System.String.StartsWith(String, ..., CultureInfo) method.
Imports System.Threading
Imports System.Globalization
Class Sample
Public Shared Sub Main()
Dim msg1 As String = "Search for the target string ""{0}"" in the string ""{1}""." & vbCrLf
Dim msg2 As String = "Using the {0} - ""{1}"" culture:"
Dim msg3 As String = " The string to search ends with the target string: {0}"
Dim result As Boolean = False
Dim ci As CultureInfo
' Define a target string to search for.
' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
Dim capitalARing As String = "Å"
' Define a string to search.
' The result of combining the characters LATIN SMALL LETTER A and COMBINING
' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
Dim aRingXYZ As String = "å" & "xyz"
' Clear the screen and display an introduction.
Console.Clear()
' Display the string to search for and the string to search.
Console.WriteLine(msg1, capitalARing, aRingXYZ)
' Search using English-United States culture.
ci = New CultureInfo("en-US")
Console.WriteLine(msg2, ci.DisplayName, ci.Name)
Console.WriteLine("Case sensitive:")
result = aRingXYZ.StartsWith(capitalARing, False, ci)
Console.WriteLine(msg3, result)
Console.WriteLine("Case insensitive:")
result = aRingXYZ.StartsWith(capitalARing, True, ci)
Console.WriteLine(msg3, result)
Console.WriteLine()
' Search using Swedish-Sweden culture.
ci = New CultureInfo("sv-SE")
Console.WriteLine(msg2, ci.DisplayName, ci.Name)
Console.WriteLine("Case sensitive:")
result = aRingXYZ.StartsWith(capitalARing, False, ci)
Console.WriteLine(msg3, result)
Console.WriteLine("Case insensitive:")
result = aRingXYZ.StartsWith(capitalARing, True, ci)
Console.WriteLine(msg3, result)
End Sub
End Class
'
'Note: This code example was executed on a console whose user interface
'culture is "en-US" (English-United States).
'
'Search for the target string "Å" in the string "a°xyz".
'
'Using the English (United States) - "en-US" culture:
'Case sensitive:
' The string to search ends with the target string: False
'Case insensitive:
' The string to search ends with the target string: True
'
'Using the Swedish (Sweden) - "sv-SE" culture:
'Case sensitive:
' The string to search ends with the target string: False
'Case insensitive:
' The string to search ends with the target string: False
'
Комментарии
Этот метод сравнивает value параметр с подстрокой в начале этой строки, которая имеет ту же длину, что valueи значение, указывающее, равны ли они. Чтобы быть равным, value должен быть пустой строкой (String.Empty), должен быть ссылкой на этот же экземпляр или должен соответствовать началу этого экземпляра.
Этот метод выполняет сравнение с использованием указанного регистра и языка и региональных параметров.