String.Copy(String) メソッド

定義

注意事項

This API should not be used to create mutable strings. See https://go.microsoft.com/fwlink/?linkid=2084035 for alternatives.

指定した String と同じ値を使用して、String の新しいインスタンスを作成します。

public:
 static System::String ^ Copy(System::String ^ str);
[System.Obsolete("This API should not be used to create mutable strings. See https://go.microsoft.com/fwlink/?linkid=2084035 for alternatives.")]
public static string Copy (string str);
public static string Copy (string str);
[<System.Obsolete("This API should not be used to create mutable strings. See https://go.microsoft.com/fwlink/?linkid=2084035 for alternatives.")>]
static member Copy : string -> string
static member Copy : string -> string
Public Shared Function Copy (str As String) As String

パラメーター

str
String

コピーする文字列。

戻り値

str と同じ値を持つ新しい文字列。

属性

例外

strnullです。

注釈

メソッドは CopyString 元の文字列と同じ値を持つが、別のオブジェクト参照を表すオブジェクトを返します。 これは、既存の文字列参照を追加のオブジェクト変数に割り当てる代入操作とは異なります。

重要

.NET Core 3.0 以降、このメソッドは廃止されました。 ただし、.NET 実装での使用はお勧めしません。 特に、.NET Core 3.0 での文字列のインターンが変更されたため、場合によっては Copy 、メソッドは新しい文字列を作成せず、単に既存のインターン文字列への参照を返します。

メソッドを呼び出 Copy す理由に応じて、いくつかの代替手段があります。

  • 文字列を変更する操作で別の文字列インスタンスを使用する場合は、元の文字列インスタンスを使用します。 文字列は不変であるため、文字列操作によって新しい文字列インスタンスが作成され、元の文字列は影響を受けません。 この場合、新しい文字列参照を元の文字列変数に割り当てないようにしてください。 具体的な例を次に示します。

    var original = "This is a sentence. This is a second sentence.";
    var sentence1 = original.Substring(0, original.IndexOf(".") + 1);
    Console.WriteLine(original);
    Console.WriteLine(sentence1);
    // The example displays the following output:
    //    This is a sentence. This is a second sentence.
    //    This is a sentence.
    
    let original = "This is a sentence. This is a second sentence."
    let sentence1 = original.Substring(0, original.IndexOf "." + 1)
    printfn $"{original}"
    printfn $"{sentence1}"
    // The example displays the following output:
    //    This is a sentence. This is a second sentence.
    //    This is a sentence.
    
    Dim original = "This is a sentence. This is a second sentence."
    Dim sentence1 = original.Substring(0, original.IndexOf(".") + 1)
    Console.WriteLine(original)
    Console.WriteLine(sentence1)
    ' The example displays the following output:
    '    This is a sentence. This is a second sentence.
    '    This is a sentence.
    

    この場合、 メソッドを Copy 呼び出して新しい文字列を作成してから、 メソッドを Substring 呼び出すと、不必要に新しい文字列インスタンスが作成されます。

  • 元の文字列と同じ内容を持つ変更可能なバッファーを作成する場合は、 または StringBuilder.StringBuilder(String) コンストラクターをString.ToCharArray呼び出します。 次に例を示します。

    private static void UseMutableBuffer()
    {
        var original = "This is a sentence. This is a second sentence.";
        var chars = original.ToCharArray();
        var span = new Span<char>(chars);
        var slice = span.Slice(span.IndexOf('.'), 3);
        slice = MergeSentence(slice);
        Console.WriteLine($"Original string: {original}");
        Console.WriteLine($"Modified string: {span.ToString()}");
    
        static Span<char> MergeSentence(Span<char> span)
        {
            if (span.Length == 0) return Span<char>.Empty;
    
            span[0] = ';';
            span[2] = Char.ToLower(span[2]);
            return span;
        }
    }
    // The example displays the following output:
    //    Original string: This is a sentence. This is a second sentence.
    //    Modified string: This is a sentence; this is a second sentence.
    
    let mergeSentence (span: Span<char>) =
        if span.Length = 0 then
            Span<char>.Empty
        else
            span[0] <- '\000'
            span[2] <- Char.ToLower span[2]
            span
    
    let useMutableBuffer () =
        let original = "This is a sentence. This is a second sentence."
        let chars = original.ToCharArray()
        let span = Span chars
        let slice = span.Slice(span.IndexOf '.', 3)
        let slice = mergeSentence slice
        let span = span.ToString()
        printfn $"Original string: {original}"
        printfn $"Modified string: {span}"
    // The example displays the following output:
    //    Original string: This is a sentence. This is a second sentence.
    //    Modified string: This is a sentence this is a second sentence.
    
    Private Sub UseMutableBuffer()
        Dim original = "This is a sentence. This is a second sentence."
        Dim sb = new StringBuilder(original)
        Dim index = original.IndexOf(".")
        sb(index) = ";"
        sb(index + 2) = Char.ToLower(sb(index + 2))
        Console.WriteLine($"Original string: {original}")
        Console.WriteLine($"Modified string: {sb.ToString()}")
    End Sub
    ' The example displays the following output:
    '    Original string: This is a sentence. This is a second sentence.
    '    Modified string: This is a sentence; this is a second sentence.
    
  • 安全でないコードを使用して文字列の内容を変更できるように、文字列の変更可能なコピーを作成する場合は、 メソッドを使用 Marshal.StringToHGlobalUni します。 次の例では、 メソッドを Marshal.StringToHGlobalUni 使用して、アンマネージド メモリ内のコピーされた文字列の場所へのポインターを取得し、文字列内の各文字の Unicode コード ポイントを 1 ずつインクリメントし、結果の文字列をマネージド文字列にコピーします。

    private static void UseUnmanaged()
    {
        var original = "This is a single sentence.";
        var len = original.Length; 
        var ptr = Marshal.StringToHGlobalUni(original);
        string? result;
        unsafe 
        {
            char *ch = (char *) ptr.ToPointer();
            while (len-- > 0)
            {
                char c = Convert.ToChar(Convert.ToUInt16(*ch) + 1);
                *ch++ = c;
            } 
            result = Marshal.PtrToStringUni(ptr);
            Marshal.FreeHGlobal(ptr);
        }
        Console.WriteLine($"Original string: {original}");
        Console.WriteLine($"String from interop: '{result}'");
    }
    // The example displays the following output:
    //    Original string: This is a single sentence.
    //    String from interop: 'Uijt!jt!b!tjohmf!tfoufodf/'
    
    #nowarn "9"
    open FSharp.NativeInterop
    
    let useUnmanaged () =
        let original = "This is a single sentence."
        let mutable len = original.Length 
        let ptr = Marshal.StringToHGlobalUni original
        let mutable ch = ptr.ToPointer() |> NativePtr.ofVoidPtr<char> 
        while len > 0 do
            len <- len - 1
            Convert.ToUInt16(NativePtr.read ch) + 1us
            |> Convert.ToChar
            |> NativePtr.write (NativePtr.add ch 1)
            ch <- NativePtr.add ch 1
    
        let result = Marshal.PtrToStringUni ptr
        Marshal.FreeHGlobal ptr
        printfn $"Original string: {original}"
        printfn $"String from interop: '{result}'"
    
    // The example displays the following output:
    //    Original string: This is a single sentence.
    //    String from interop: 'Uijt!jt!b!tjohmf!tfoufodf/'
    

適用対象