1

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#.

1
  • Which version of c# are you using? Commented Apr 20, 2010 at 14:10

6 Answers 6

5

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");
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Good point. For example, if this is a PATH variable that contains many occurences of C:\Data paths separated by semicolons, then Replace would replace all of them. This could be desirable or not, depending on Indigo's needs.
1

Combining LINQ and string.Replace():

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

Comments

0

String.replace would take care of that pretty easily.

Comments

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

Comments

-1

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.

1 Comment

This example is incomplete doesn't quite do what @Indigo is asking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.