當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# String.Insert()用法及代碼示例

C# String.Insert() 方法

String.Insert() 方法用於在指定索引處的現有字符串中插入一個字符串並返回一個新字符串。

用法:

    public string String.Insert(int index, string value);

該方法使用 "this" 字符串調用,即我們必須在其中插入字符串的字符串。

參數:

  • index– 表示當前字符串的索引/位置,其中新字符串value被插入。
  • value– 要插入的新字符串。

返回值:

  • string– 它返回一個新字符串,其中包含在給定索引處插入的字符串。

例:

    Input:
    string str = "IncludeHelp";
    string str1 = " programming ";
    
    Function call
    str.Insert(7, str1);

    Output:
    Include programming Help

使用 String.Insert() 方法將字符串轉換為字符數組的 C# 示例

範例1:

using System;
class IncludeHelp
{
    static void Main()
    {
        // declaring string variables
        string str = "IncludeHelp";

        // inserting space between Include and Help
        string new_string = str.Insert(7, " ");

        Console.WriteLine("str:" + str);
        Console.WriteLine("new_string:" + new_string);
    }
}

輸出

str:IncludeHelp
new_string:Include Help

範例2:

using System;
class IncludeHelp
{
    static void Main()
    {
        // declaring string variables
        string str = "IncludeHelp";
        string str1 = " programming ";

        // inserting str1 after "Include"
        string new_string = str.Insert(7, str1);

        Console.WriteLine("str:" + str);
        Console.WriteLine("new_string:" + new_string);

    }
}

輸出

str:IncludeHelp
new_string:Include programming Help


相關用法


注:本文由純淨天空篩選整理自 String.Insert() method with example in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。