简体   繁体   English

C#中的字符串拆分操作

[英]String split operations in C#

I have a string say string s ="C:\\\\Data" , I have an array which contains some strings containg "C:\\Data" in the beginning ie string[] arr = new {"C:\\\\Data\\abc.xml","C:\\\\Data\\Test\\hello.cs"}; 我有一个字符串,说string s ="C:\\\\Data" ,我有一个数组,其中包含一些开头包含“ C:\\ Data”的string[] arr = new {"C:\\\\Data\\abc.xml","C:\\\\Data\\Test\\hello.cs"};string[] arr = new {"C:\\\\Data\\abc.xml","C:\\\\Data\\Test\\hello.cs"}; .

I have to remove the string "C:\\Data" from each entry and have to combine it with another string say string fixed = "D:\\\\Data" . 我必须从每个条目中删除字符串“ C:\\ Data”,并将其与另一个字符串结合在一起,例如string fixed = "D:\\\\Data"

What is the best way to do it, please help as I am a new programmer in C#. 最好的方法是什么,请帮忙,因为我是C#的新程序员。

If you're sure that all of the elements in your array begin with "C:\\Data", then it's pretty simple: 如果您确定数组中的所有元素都以“ C:\\ Data”开头,那么这很简单:

for(int i = 0; i<arr.Length; i++)
{
   arr[i] = arr[i].Replace("C:\\Data" , "D:\\Data");
}

String.Replace is perhaps not what you need, as it would replace all the occurrences of C:\\Data in your string, whereas you need only that at the beginning . String.Replace可能不是您所需要的,因为它将替换字符串中所有出现的C:\\Data ,而仅在开始时需要

I would suggest the following: 我建议以下内容:

string s ="C:\\Data";
string s1 = "D:\\Data";
for (int i = 0; i < arr.Count; i++)
{
    if (arr[i].StartsWith(s))
        arr[i] = s1 + arr[i].Remove(s.Length);
}

结合LINQ和string.Replace():

arr.Select(s => s.Replace("C:\\Data", "D:\\Data").ToArray();

String.replace可以很轻松地解决这个问题。

for (var i=0; i < arr.Length; i++)
  arr[i] = arr[i].Replace("C:\\Data", "D:\\Data");

You could use LINQ and do 您可以使用LINQ并执行

String[] newStrings = arr.Select(oldString => fixed + oldString.Replace(s, ""))
                         .ToArray()

Note that fixed is a keyword in c# and therefore a bad choice for a variable name. 注意, fixed是c#中的关键字,因此是变量名的错误选择。

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

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