6

我有一个这样的字符串;

   string text =  "6A7FEBFCCC51268FBFF";

我有一种方法,我想插入逻辑,将 4 个字符后的连字符附加到“文本”变量。所以,输出应该是这样的;

6A7F-EBFC-CC51-268F-BFF

将连字符附加到上面的“文本”变量逻辑应该在这个方法中;

public void GetResultsWithHyphen
{
     // append hyphen after 4 characters logic goes here
}

而且我还想从给定的字符串中删除连字符,例如6A7F-EBFC-CC51-268F-BFF. 因此,从字符串逻辑中删除连字符应该在此方法中;

public void GetResultsWithOutHyphen
{
     // Removing hyphen after 4 characters logic goes here
}

如何在 C# 中执行此操作(用于桌面应用程序)?做这个的最好方式是什么? 提前欣赏大家的回答。

4

10 回答 10

7

GetResultsWithOutHyphen很容易(并且应该返回 astring而不是void

public string GetResultsWithOutHyphen(string input)
{
    // Removing hyphen after 4 characters logic goes here
    return input.Replace("-", "");
}

对于GetResultsWithHyphen,可能有更巧妙的方法来做到这一点,但这里有一种方法:

public string GetResultsWithHyphen(string input)
{

    // append hyphen after 4 characters logic goes here
    string output = "";
    int start = 0;
    while (start < input.Length)
    {
        output += input.Substring(start, Math.Min(4,input.Length - start)) + "-";
        start += 4;
    }
    // remove the trailing dash
    return output.Trim('-');
}
于 2012-07-11T16:29:27.187 回答
5

使用正则表达式:

public String GetResultsWithHyphen(String inputString)
{
     return Regex.Replace(inputString, @"(\w{4})(\w{4})(\w{4})(\w{4})(\w{3})",
                                       @"$1-$2-$3-$4-$5");
}

并删除:

public String GetResultsWithOutHyphen(String inputString)
{
    return inputString.Replace("-", "");
}
于 2012-07-11T16:33:19.457 回答
2

这是我能想到的最短的正则表达式。它适用于任何长度的字符串。请注意, \B 标记将阻止它在字符串末尾匹配,因此您不必像上面的某些答案那样修剪额外的连字符。

    using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "6A7FEBFCCC51268FBFF";
            for (int i = 0; i <= text.Length;i++ )
                Console.WriteLine(hyphenate(text.Substring(0, i))); 
        } 

        static string hyphenate(string s)
        {
            var re = new Regex(@"(\w{4}\B)");
            return re.Replace (s, "$1-");
        }

        static string dehyphenate (string s)
        {
            return s.Replace("-", "");
        }
    } 
}
于 2012-07-11T16:41:01.593 回答
1
var hyphenText = new string(
  text
 .SelectMany((i, ch) => i%4 == 3 && i != text.Length-1 ? new[]{ch, '-'} : new[]{ch})
 .ToArray()

)

于 2012-07-11T16:29:47.470 回答
1
public static string GetResultsWithHyphen(string str) {
  return Regex.Replace(str, "(.{4})", "$1-");
  //if you don't want trailing -
  //return Regex.Replace(str, "(.{4})(?!$)", "$1-");
}

public static string GetResultsWithOutHyphen(string str) {            
  //if you just want to remove the hyphens:
  //return input.Replace("-", "");
  //if you REALLY want to remove hyphens only if they occur after 4 places:
   return Regex.Replace(str, "(.{4})-", "$1");
}
于 2012-07-11T16:37:37.680 回答
1

类似于:

public string GetResultsWithHyphen(string inText)
{
    var counter = 0;
    var outString = string.Empty;
    while (counter < inText.Length)
    {
        if (counter % 4 == 0)
            outString = string.Format("{0}-{1}", outString, inText.Substring(counter, 1));
        else
            outString += inText.Substring(counter, 1);
        counter++;
    }
    return outString;
}

这是粗略的代码,在语法上可能并不完美

于 2012-07-11T16:40:01.983 回答
0

对于删除:

String textHyphenRemoved=text.Replace('-',''); should remove all of the hyphens

用于添加

StringBuilder strBuilder = new StringBuilder();
int startPos = 0;
for (int i = 0; i < text.Length / 4; i++)
{
    startPos = i * 4;
    strBuilder.Append(text.Substring(startPos,4));

    //if it isn't the end of the string add a hyphen
    if(text.Length-startPos!=4)
        strBuilder.Append("-");
}
//add what is left
strBuilder.Append(text.Substring(startPos, 4));
string textWithHyphens = strBuilder.ToString();

请注意,我的添加代码未经测试。

于 2012-07-11T16:36:35.573 回答
0

GetResultsWithOutHyphen method

public string GetResultsWithOutHyphen(string input)
{

     return input.Replace("-", "");

}

GetResultsWithOutHyphen method

您可以传递一个变量而不是四个以获得灵活性。

public string GetResultsWithHyphen(string input)
{

string output = "";
        int start = 0;
        while (start < input.Length)
        {
            char bla = input[start];
            output += bla;
            start += 1;
            if (start % 4 == 0)
            {
                output += "-";    
            }
        }
return output;
}
于 2012-07-11T17:16:25.853 回答
0

当我有一个社会安全号码 (123456789) 的值并需要它在列表框中显示为 (123-45-6789) 时,这对我有用。

ListBox1.Items.Add("SS Number :  " & vbTab & Format(SSNArray(i), "###-##-####"))

在这种情况下,我有一系列社会安全号码。这行代码更改了格式以放入连字符。

于 2017-05-08T21:43:20.390 回答
0

被调用者

public static void Main()
{
    var text = new Text("THISisJUSTanEXAMPLEtext");
    var convertText = text.Convert();
    Console.WriteLine(convertText);
}

呼叫者

public class Text
{
    private string _text;
    private int _jumpNo = 4;
    
    public Text(string text)
    {
        _text = text;
    }
    
    public Text(string text, int jumpNo)
    {
        _text = text;
        _jumpNo = jumpNo < 1 ? _jumpNo : jumpNo;
    }
    
    public string Convert()
    {
        if (string.IsNullOrEmpty(_text)) 
        {
            return string.Empty;
        }
        
        if (_text.Length < _jumpNo)
        {
            return _text;   
        }
        
        var convertText = _text.Substring(0, _jumpNo);
        int start = _jumpNo;
        while (start < _text.Length)
        {
            convertText += "-" + _text.Substring(start, Math.Min(_jumpNo, _text.Length - start));
            start += _jumpNo;
        }
        
        return convertText;
    }
}
于 2022-02-08T10:23:14.147 回答