简体   繁体   English

用另一个替换字符串的第一部分

[英]Replacing first part of string by another

I need to replace multiple file names in a folder. 我需要替换一个文件夹中的多个文件名。 Here is one of the files: 这是文件之一:

Abc.CDE.EFG

I need to replace the first part of the string before the dot ("ABC") and replace it with: "zef". 我需要将字符串的第一部分替换为点(“ ABC”)之前的部分,并替换为:“ zef”。

Any ideas? 有任何想法吗? I found this but it takes out the dot and not sure how to add the "zef". 我发现了这一点,但它会删除点,并且不确定如何添加“ zef”。

var input = _FileInfo.ToString(); 
var output = input.Substring(input.IndexOf(".").Trim())

Since the question is tagged with regex, you can use a regular expression like so: 由于问题是用正则表达式标记的,因此您可以使用如下正则表达式:

var input = "abc.def.efg";
var pattern = "^[^\\.]+";
var replacement = "zef";
var rgx = new Regex(pattern);
var output = rgx.Replace(input, replacement);

Source: https://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx 来源: https : //msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx

You are almost there, try: 您快要准备好了,请尝试:

string myString = "Abc.CDE.EFG";    

//This splits your string into an array with 3 items
//"Abc", "CDE" and "EFG"    
var stringArray = myString.Split('.');  

//Now modify the first item by changing it to "zef" 
stringArray[0] = "zef"; 

//Then we rebuild the string by joining the array together
//delimiting each group by a period
string newString = string.Join(".", stringArray);

With this solution you can independently access any of the "blocks" just by referencing the array by index. 使用此解决方案,您只需通过索引引用数组即可独立访问任何“块”。

Fiddle here 在这里摆弄

Try this: 尝试这个:

    var input = _FileInfo.ToString(); 
    var output = "zef" + input.Substring(input.IndexOf("."));

If you know the length of the first string , you can replace mentioning number of characters starting from position until the length you want to replace else. 如果您知道第一个字符串的长度,则可以从位置开始替换要提及的字符数,直到要替换的长度为止。

string s = "Abc.CDE.EFG";
                string [] n = s.Split('.');
                n[0] = "ZEF";
                string p = string.Join(".",n);
                Console.WriteLine(p);
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM