gpt4 book ai didi

c# - 从字符串数组创建更大的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 12:11:05 25 4
gpt4 key购买 nike

我有一个字符串数组,看起来像这样

var input = new [] { "AB-PQ", "PQ-EF", "EF=CD", "CD-IJ", "IJ=XY", "XY-JK" };

我想要一个像这样的字符串输出

var output = "AB-PQ-EF=CD-IJ=XY-JK"

我想知道是否有更好的方法来执行此操作,而不是使用强力 for 循环,然后使用字符串生成器拆分和组合。

我的业务用例:我的业务用例是这样的,给定的字符串表示包含多个城市的 route 两个城市之间的一系列链接。 “-”表示公路连接,“=”表示铁路连接。城市代码可以是任意长度。

最佳答案

这个有效:

var input = new [] { "AB-PQ", "PQ-EF", "EF=CD", "CD-IJ", "IJ=XY", "XY-JK" };

var output = String.Join("",
input.Take(1).Concat(new [] { String.Join("", input.Skip(1).Select(x => x.Substring(2))) }));

我不喜欢它,但它确实有效。它生成 "AB-PQ-EF=CD-IJ=XY-JK"


尝试将此作为更强大的替代方案:

void Main()
{
var input = new[] { "AB-PQ", "PQ-XYZ", "XYZ=CD", "CD-A", "A=XY", "XY-JK" };

var output =
input
.Select(i => new Segment(i))
.Aggregate(
"",
(a, x) => a + x.ToString().Substring(a == "" ? 0 : x.Origin.Length));
}

public enum Mode
{
Road, Rail
}

public sealed class Segment : IEquatable<Segment>
{
private readonly string _origin;
private readonly Mode _mode;
private readonly string _destination;

public string Origin { get { return _origin; } }
public Mode Mode { get { return _mode; } }
public string Destination { get { return _destination; } }

public Segment(string descriptor)
{
var parts = descriptor.Split('-', '=');
if (parts.Length != 2)
{
throw new System.ArgumentException("Segment descriptor must contain '=' or '-'.");
}
_origin = parts[0];
_mode = descriptor.Contains("=") ? Mode.Rail : Mode.Road;
_destination = parts[1];
}

public Segment(string origin, Mode mode, string destination)
{
_origin = origin;
_mode = mode;
_destination = destination;
}

public override bool Equals(object obj)
{
if (obj is Segment)
return Equals((Segment)obj);
return false;
}

public bool Equals(Segment obj)
{
if (obj == null) return false;
if (!EqualityComparer<string>.Default.Equals(_origin, obj._origin)) return false;
if (!EqualityComparer<Mode>.Default.Equals(_mode, obj._mode)) return false;
if (!EqualityComparer<string>.Default.Equals(_destination, obj._destination)) return false;
return true;
}

public override int GetHashCode()
{
int hash = 0;
hash ^= EqualityComparer<string>.Default.GetHashCode(_origin);
hash ^= EqualityComparer<Mode>.Default.GetHashCode(_mode);
hash ^= EqualityComparer<string>.Default.GetHashCode(_destination);
return hash;
}

public override string ToString()
{
return $"{_origin}{(_mode == Mode.Rail ? "=" : "-")}{_destination}";
}

public static bool operator ==(Segment left, Segment right)
{
if (object.ReferenceEquals(left, null))
{
return object.ReferenceEquals(right, null);
}

return left.Equals(right);
}

public static bool operator !=(Segment left, Segment right)
{
return !(left == right);
}
}

关于c# - 从字符串数组创建更大的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52289477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com