Reputation: 815
I have an char array. I want to remove an element at a certain position of the array.
Lets say I have this char array: OVERFLOW
I want to remove R from the array above and resize the char array so the word will be: OVEFLOW
I want to be able to add also a new letter to the array at a certain position. Lets say I want to add the letter T so the word will be like: OVETFLOW
I don't just want to replace two letters. I want to first completely remove and then add the letter at a different position.
I have tried to solve the problem with the Remove()
method which is used for string arrays. But I have not figured it out which way is the best way to solve the problem.
Upvotes: 5
Views: 28957
Reputation: 402
As a quick example:
string str = "OWERFLOW";
char[] array = str.ToCharArray();
char[] array2 = RemveFromArray(array, 'R');
char[] array3 = InsertIntoArray(array2, 'T', 3);
char[] array4 = RemveFromArrayAt(array, 3);
static char[] RemveFromArray(char[] source, char value)
{
if (source == null)
return null;
char[] result = new char[source.Length];
int resultIdx = 0;
for (int ii = 0; ii < source.Length; ii++)
{
if(source[ii] != value)
result[resultIdx++] = source[ii];
}
return result.Take(resultIdx).ToArray();
}
static char[] InsertIntoArray(char[] source, char value, int insertAt)
{
if (source == null || insertAt > source.Length)
return null;
char[] result = new char[source.Length + 1];
Array.Copy(source, result, insertAt);
result[insertAt] = value;
Array.Copy(source, insertAt, result, insertAt + 1, source.Length - insertAt);
return result;
}
static char[] RemveFromArrayAt(char[] source, int removeAt)
{
if (source == null || removeAt > source.Length)
return null;
char[] result = new char[source.Length - 1];
Array.Copy(source, result, removeAt);
Array.Copy(source, removeAt + 1, result, removeAt, source.Length - removeAt - 1);
return result;
}
Upvotes: 1
Reputation: 2387
An alternative way:
string str = "OVERFLOW";
var arr=str.ToList();
arr.Remove('F');
arr.Insert(3, 'T');
str =new string(arr.ToArray());
Upvotes: 1
Reputation: 222582
var theString = "OVERFLOW";
var aStringBuilder = new StringBuilder(theString);
aStringBuilder.Remove(3, 1);
aStringBuilder.Insert(3, "T");
theString = aStringBuilder.ToString();
Upvotes: 6
Reputation: 26209
Try This:
char[] myCharArray = new char[] { 'O', 'V', 'E', 'R', 'F', 'F', 'L', 'O', 'W' };
string str = new string(myCharArray);
int index = str.IndexOf('R');
str=str.Remove(index,1);
str=str.Insert(index, "Z");
myCharArray = str.ToCharArray();
Upvotes: 4