自定义字符串替换方法

时间:2015-09-11 17:30:25

标签: c# asp.net regex

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

示例:

Cars-are-equipped-with-controls-used-for-driving-parking-passenger-comfort-and-
safety-and-controlling-a-variety-of-lights-As-of-the-2010s-controls-have-been-
added-to-vehicles-making-them-more-complex


part = "safety-and-controlling"
/* safety is fixed */

chars = "(,'')"

output = "safety(and, 'controlling')"

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

3 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:0)

尝试这样的事情:

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

答案 2 :(得分:0)

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

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允许您就地操作文本的单个字符。

一种非常直接的方法只是扫描字符串&#34; - &#34;明确地:

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();

请注意,这两种方法永远不会拆分或连接字符串。第二种方法尤其是内存效率。