String.Remove Метод

Определение

Возвращает новую строку, в которой удаляется указанное число символов из текущей строки.

Перегрузки

Имя Описание
Remove(Int32, Int32)

Возвращает новую строку, в которой было удалено указанное число символов в текущем экземпляре, начиная с указанной позиции.

Remove(Int32)

Возвращает новую строку, в которой были удалены все символы в текущем экземпляре, начиная с указанной позиции и продолжая последнюю позицию.

Remove(Int32, Int32)

Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs

Возвращает новую строку, в которой было удалено указанное число символов в текущем экземпляре, начиная с указанной позиции.

public:
 System::String ^ Remove(int startIndex, int count);
public string Remove(int startIndex, int count);
member this.Remove : int * int -> string
Public Function Remove (startIndex As Integer, count As Integer) As String

Параметры

startIndex
Int32

Отсчитываемая от нуля позиция для начала удаления символов.

count
Int32

Число удаленных символов.

Возвращаемое значение

Новая строка, эквивалентная этому экземпляру, за исключением удаленных символов.

Исключения

startIndex Либо count меньше нуля.

–или–

startIndex плюс count укажите позицию за пределами этого экземпляра.

Примеры

В следующем примере показано, как удалить промежуточное имя из полного имени.

using System;

public class RemoveTest
{
    public static void Main()
    {

        string name = "Michelle Violet Banks";

        Console.WriteLine("The entire name is '{0}'", name);

        // Remove the middle name, identified by finding the spaces in the name.
        int foundS1 = name.IndexOf(" ");
        int foundS2 = name.IndexOf(" ", foundS1 + 1);

        if (foundS1 != foundS2 && foundS1 >= 0)
        {
            name = name.Remove(foundS1 + 1, foundS2 - foundS1);

            Console.WriteLine("After removing the middle name, we are left with '{0}'", name);
        }
    }
}
// The example displays the following output:
//       The entire name is 'Michelle Violet Banks'
//       After removing the middle name, we are left with 'Michelle Banks'
let name = "Michelle Violet Banks"

printfn $"The entire name is '{name}'"

// Remove the middle name, identified by finding the spaces in the name.
let foundS1 = name.IndexOf " "
let foundS2 = name.IndexOf(" ", foundS1 + 1)

if foundS1 <> foundS2 && foundS1 >= 0 then
    let name = name.Remove(foundS1 + 1, foundS2 - foundS1)

    printfn $"After removing the middle name, we are left with '{name}'"
// The example displays the following output:
//       The entire name is 'Michelle Violet Banks'
//       After removing the middle name, we are left with 'Michelle Banks'
Public Class RemoveTest
    
    Public Shared Sub Main()
        Dim name As String = "Michelle Violet Banks"
                
        Console.WriteLine("The entire name is '{0}'", name)
        Dim foundS1 As Integer = name.IndexOf(" ")
        Dim foundS2 As Integer = name.IndexOf(" ", foundS1 + 1)
        If foundS1 <> foundS2 And foundS1 >= 0 Then
            
            ' remove the middle name, identified by finding the spaces in the middle of the name...    
            name = name.Remove(foundS1 + 1, foundS2 - foundS1)
            
            Console.WriteLine("After removing the middle name, we are left with '{0}'", name)
        End If
    End Sub
End Class 
' The example displays the following output:
'       The entire name is 'Michelle Violet Banks'
'       After removing the middle name, we are left with 'Michelle Banks'

Комментарии

В .NET Framework строки основаны на нулях. Значение startIndex параметра может варьироваться от нуля до одного, чем длина строкового экземпляра.

Note

Этот метод не изменяет значение текущего экземпляра. Вместо этого он возвращает новую строку, в которой было удалено число символов, указанных count параметром. Символы удаляются по позиции, указанной в параметре startIndex.

См. также раздел

Применяется к

Remove(Int32)

Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs
Исходный код:
String.Manipulation.cs

Возвращает новую строку, в которой были удалены все символы в текущем экземпляре, начиная с указанной позиции и продолжая последнюю позицию.

public:
 System::String ^ Remove(int startIndex);
public string Remove(int startIndex);
member this.Remove : int -> string
Public Function Remove (startIndex As Integer) As String

Параметры

startIndex
Int32

Отсчитываемая от нуля позиция для начала удаления символов.

Возвращаемое значение

Новая строка, эквивалентная этой строке, за исключением удаленных символов.

Исключения

startIndex меньше нуля.

–или–

startIndex больше длины этого экземпляра.

Примеры

В следующем примере демонстрируется Remove метод. Следующий к последнему регистру удаляет весь текст, начиная с указанного индекса через конец строки. Последний случай удаляет три символа, начиная с указанного индекса.

// This example demonstrates the String.Remove() method.
using System;

class Sample
{
    public static void Main()
    {
        string s = "abc---def";

        Console.WriteLine("Index: 012345678");
        Console.WriteLine("1)     {0}", s);
        Console.WriteLine("2)     {0}", s.Remove(3));
        Console.WriteLine("3)     {0}", s.Remove(3, 3));
    }
}
/*
This example produces the following results:

Index: 012345678
1)     abc---def
2)     abc
3)     abcdef

*/
// This example demonstrates the String.Remove() method.
let s = "abc---def"

printfn "Index: 012345678"
printfn $"1)     {s}"
printfn $"2)     {s.Remove 3}"
printfn $"3)     {s.Remove(3, 3)}"
(*
This example produces the following results:

Index: 012345678
1)     abc---def
2)     abc
3)     abcdef

*)
' This example demonstrates the String.Remove() method.
Class Sample
   Public Shared Sub Main()
      Dim s As String = "abc---def"
      '
      Console.WriteLine("Index: 012345678")
      Console.WriteLine("1)     {0}", s)
      Console.WriteLine("2)     {0}", s.Remove(3))
      Console.WriteLine("3)     {0}", s.Remove(3, 3))
   End Sub
End Class
'
'This example produces the following results:
'
'Index: 012345678
'1)     abc---def
'2)     abc
'3)     abcdef
'

Комментарии

В .NET Framework строки основаны на нулях. Значение startIndex параметра может варьироваться от нуля до длины экземпляра строки.

Note

Этот метод не изменяет значение текущего экземпляра. Вместо этого он возвращает новую строку, в которой все символы из позиции startIndex в конец исходной строки были удалены.

См. также раздел

Применяется к