如何在字符串中插入“ - ”?

时间:2011-08-18 15:50:00

标签: c# string

我有一个字符串,如下所示:12345,此123456或此:1234567

我想让每个字符串看起来像这样:123-45,这个:1234-56或者这个:12345-67

我怎样才能在C#中做到这一点?

4 个答案:

答案 0 :(得分:13)

string myString = "1234567";   
if(myString.Length > 1)
   string dashed = myString.Insert(myString.Length - 2, "-");

编辑:根据评论添加了检查,但取决于应如何处理此类字符串。 (例如,即使长度= 2,也会破灭)。

答案 1 :(得分:9)

看看String.Format(),我猜你想要像String.Format(“{0:## - ##}”,< value>);

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

powershell显示的示例,它使用相同的corelibs

PS C:\Users\Phyx> [string]::Format("{0:##-##}",1234)
12-34
PS C:\Users\Phyx> [string]::Format("{0:##-##}",123445)
1234-45
PS C:\Users\Phyx> [string]::Format("{0:##-##}",12)
-12
PS C:\Users\Phyx> [string]::Format("{0:0#-##}",12)
00-12
PS C:\Users\Phyx> [string]::Format("{0:##-##}",122)
1-22

答案 2 :(得分:6)

string s = "teststring";
string newString = s.Insert(s.Length-2,"-");

这假设你希望' - '从最后出现两个: - )

这可能很方便(未经测试)

    /// <summary>
    /// Takes a string and and inserts a spacer character at 
    /// a specifed distance from the end
    /// </summary>
    /// <param name="input">string to modify</param>
    /// <param name="spacer">string to insert</param>
    /// <param name="positionFromEnd">insertion point</param>
    /// <returns></returns>
    protected string AddSpacer(string input, string spacer, int positionFromEnd)
    {
        string outputString = string.Empty;

        if (input.Length >= positionFromEnd)
        {
            outputString = input.Insert(input.Length - positionFromEnd, spacer);
        }
        else
        {
            throw new Exception("The position you tried to insert the spacer into doesn't exist");
        }

        return outputString;
    }

答案 3 :(得分:6)

我假设您想在字符串结尾之前添加两个字符。

string number = "12345";

if(number.Length > 2)
    string result = number.Insert(number.Length-2, "-");
else
    //error checking