【问题标题】:Custom string replace method自定义字符串替换方法
【发布时间】:2015-09-11 17:30:24
【问题描述】:

我想要一个字符串替换的方法。

例子:

汽车配备控制用于驾驶停车乘客舒适和- 安全和控制各种灯-作为-of-the-2010s-controls-have-been- 添加到车辆中,使它们更复杂 part = "安全和控制" /* 安全是固定的 */ 字符 = "(,'')" 输出=“安全(和,'控制')”

我该怎么办。有什么想法吗?

【问题讨论】:

  • 您已将原来的简单问题修改为不再具有任何意义的形式。请提供完整的上下文并更好地提出您的问题。现在没有办法用如此有限的信息来回答这个问题。

标签: c# asp.net regex


【解决方案1】:

假设部分的数量等于chars 字符串的长度,您可以使用 LINQ 轻松解决此问题。

vehicle.Split('-').Zip(chars, (x, y) => x + y).Aggregate("", (x, y) => x + y);

【讨论】:

  • 对 linq 的使用非常好。使用string.Join 可能比使用Aggregate 更明显。
  • @Matthew 好点。我正在讨论改用它,但认为这种形式更优雅。
【解决方案2】:

试试这样的:

var vehicleArray = vehicle.Split('-');
var output = vehicleArray[0] + "(" + vehicleArray[1] + ", " +vehicleArray[2] + "@" + vehicleArray[3] + "." + vehicleArray[4] + ")";

【讨论】:

    【解决方案3】:

    您可以使用正则表达式来查找“-”的位置。

    string vehicle = "car-blue-diesel-ford-com-";
    string chars = "(,@.)";
    
    MatchCollection matches = Regex.Matches(vehicle, "-");
    var sb = new StringBuilder(vehicle);
    if (matches.Count != chars.Length) {
        throw new ArgumentException("Supply the right number of replacement chars");
    }
    for (int i = 0; i < matches.Count; i++) {
        sb[matches[i].Index] = chars[i];
    }
    string output = sb.ToString(); // "car(blue,diesel@ford.com)"
    

    StringBuilder 允许您就地操作文本的单个字符。


    一种非常直接的方法只是显式扫描字符串中的“-”:

    var sb = new StringBuilder(vehicle);
    for (int i = 0, c = 0; i < sb.Length && c < chars.Length; i++) {
        if (sb[i] == '-') {
            sb[i] = chars[c++];
        }
    }
    string output = sb.ToString();
    

    请注意,这两种方法从不拆分或连接字符串。第二种方法特别节省内存。

    【讨论】:

      猜你喜欢
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 2014-04-21
      相关资源
      最近更新 更多