Reputation: 375
I have a string say string s ="C:\\Data"
, I have an array which contains some strings containg "C:\Data" in the beginning i.e. 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"
.
What is the best way to do it, please help as I am a new programmer in C#.
Upvotes: 1
Views: 223
Reputation: 35584
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.
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);
}
Upvotes: 2
Reputation: 7870
Combining LINQ and string.Replace():
arr.Select(s => s.Replace("C:\\Data", "D:\\Data").ToArray();
Upvotes: 1
Reputation: 25270
for (var i=0; i < arr.Length; i++)
arr[i] = arr[i].Replace("C:\\Data", "D:\\Data");
Upvotes: 0
Reputation: 103740
If you're sure that all of the elements in your array begin with "C:\Data", then it's pretty simple:
for(int i = 0; i<arr.Length; i++)
{
arr[i] = arr[i].Replace("C:\\Data" , "D:\\Data");
}
Upvotes: 5
Reputation: 25563
You could use LINQ and do
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.
Upvotes: -1