How to remove a word say "code" from myArray[1] and NOT the full myArray[1].
string[] myArray = new string[3];
myArray[0] = "Hello World";
myArray[1] = "This is a sample code";
myArray[2] = "Delete me";
How to remove a word say "code" from myArray[1] and NOT the full myArray[1].
string[] myArray = new string[3];
myArray[0] = "Hello World";
myArray[1] = "This is a sample code";
myArray[2] = "Delete me";
Using the Replace
method
myArray[1] = myArray[1].Replace("code", "");
More about Replace
- https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=net-6.0
You could use String.Replace()
to substitute the target word with an empty string:
string[] myArray = new string[3];
myArray[0] = "Hello World";
myArray[1] = "This is a sample code";
myArray[2] = "Delete me";
foreach(var s in myArray) {
Console.WriteLine(s);
}
Console.WriteLine("=================");
// One specific entry
myArray[1] = myArray[1].Replace("code", "");
foreach(var s in myArray) {
Console.WriteLine(s);
}
Console.WriteLine("=================");
// All entries (if there were multiple)
for(int i = 0; i < myArray.Length; i++) {
myArray[i] = myArray[i].Replace("code", "");
}
foreach(var s in myArray) {
Console.WriteLine(s);
}
Hello World
This is a sample code
Delete me
=================
Hello World
This is a sample
Delete me
=================
Hello World
This is a sample
Delete me
There are many ways to do this, some of which are already mentioned. Here's an alternative solution using an extension routine.
public static class Extensions
{
public static void ReplaceText(this string[] array, string word, int index = 0, string newWord = "", bool replaceAll = false)
{
if (array?.Length > 0 && word != null)
{
if (replaceAll)
{
for (int i = 0; i <= array.Length - 1; i++)
{
// You could check if it contains the
// word before trying to replace it
array[i] = array[i].Replace(word, newWord);
}
}
else
{
if (array.Length >= index)
array[index] = array[index].Replace(word, newWord);
}
}
}
}
Example Usage:
myArray.ReplaceText("code", 1); //replace just the word at that index
myArray.ReplaceText("code", replaceAll: true); //replace the word in all index's
Also worth noting, look into using List if you can, they are much easier to work with and manage than arrays.