How to add characters to a string in C#

前端 未结 4 784
时光说笑
时光说笑 2021-01-21 03:13

Problem: I would like add characters to a phone.

So instead of displaying ###-###-####, I would like to display (###) ###-####.

I tried the foll

相关标签:
4条回答
  • 2021-01-21 03:22

    It's worth noting that strings are immutable in C#.. meaning that if you attempt to modify one you'll always be given a new string object.

    One route would be to convert to a number (as a sanity check) then format the string

    var result = String.Format("{0:(###) ###-####}", double.Parse("8005551234"))
    

    If you'd rather not do the double-conversion then you could do something like this:

    var result = String.Format("({0}) {1}-{2}", x.Substring(0 , 3), x.Substring(3, 3), x.Substring(6));
    

    Or, if you already have the hyphen in place and really just want to jam in the parenthesis then you can do something like this:

    var result = x.Insert(3, ")").Insert(0, "(");
    
    0 讨论(0)
  • 2021-01-21 03:23

    I would do something like this:

    string FormatPhoneNumber(string phoneNumber)
    {
        if (string.IsNullOrEmpty(phoneNumber))
            throw new ArgumentNullException(nameof(phoneNumber));
    
        var phoneParts = phoneNumber.Split('-');
        if (phoneParts.Length < 3)
            throw new ArgumentException("Something wrong with the input number format", nameof(phoneNumber));
    
        var firstChar = phoneParts[0].First();
        var lastChar = phoneParts[0].Last();
        if (firstChar == '(' && lastChar == ')')
            return phoneNumber;
        else if (firstChar == '(')
            return $"{phoneParts[0]})-{phoneParts[1]}-{phoneParts[2]}";
        else if (lastChar == ')') 
            return $"({phoneParts[0]}-{phoneParts[1]}-{phoneParts[2]}";
    
        return $"({phoneParts[0]})-{phoneParts[1]}-{phoneParts[2]}";
    }
    

    You would use it like this:

    string n = "123-123-1234";
    var formattedPhoneNumber = FormatPhoneNumber(n);
    
    0 讨论(0)
  • 2021-01-21 03:37

    To insert string in particular position you can use Insert function.

    Here is an example:

    string phone = "111-222-8765";
    phone = phone.Insert(0, "("); // (111-222-8765
    phone = phone.Insert(3, ")"); // (111)-222-8765
    
    0 讨论(0)
  • 2021-01-21 03:40

    You can use a regular expression to extract the digit groups (regardless of - or () and then output in your desired format:

    var digitGroups = Regex.Matches(x, @"(\d{3})-?(\d{3})-?(\d{4})")[0].Groups.Cast<Group>().Skip(1).Select(g => g.Value).ToArray();
    
    var ans = $"({digitGroups[0]}) {digitGroups[1]}-{digitGroups[2]}";
    
    0 讨论(0)
提交回复
热议问题