Remove a letter from a character array

20,226

Solution 1

var theString = "OVERFLOW";
var aStringBuilder = new StringBuilder(theString);
aStringBuilder.Remove(3, 1);
aStringBuilder.Insert(3, "T");
theString = aStringBuilder.ToString();

Solution 2

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

Solution 3

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;
}
Share:
20,226
EM10
Author by

EM10

Updated on March 06, 2020

Comments

  • EM10
    EM10 about 4 years

    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.

  • EM10
    EM10 about 10 years
    I don't want to replace two letters. I want to completely remove one letter and then add another letter at a different position.