character postion replacemenet
-
hello! I have a following string.
string str="flower pot";
In above string i want to replace the position of the character.
eg: "o" replace with its just next character.
my new string is shown like:
"flwoer pto"
thanx
public void RelocateChar(ref string text, int pos1, int pos2)
{
char[] supportArray = text.ToCharArray();
char supportChar;supportChar = supportArray[pos2];
supportArray[pos2] = supportArray[pos1];
supportArray[pos1] = supportChar;
text = new string(supportArray);
}Maybe there are better solutions, but this one should work.
-
public void RelocateChar(ref string text, int pos1, int pos2)
{
char[] supportArray = text.ToCharArray();
char supportChar;supportChar = supportArray[pos2];
supportArray[pos2] = supportArray[pos1];
supportArray[pos1] = supportChar;
text = new string(supportArray);
}Maybe there are better solutions, but this one should work.
Have a look through this code and see whether it solves your problem. private void button1_Click(object sender, EventArgs e) { string str = "flower pot"; MessageBox.Show("The source string " + str + System.Environment.NewLine + System.Environment.NewLine + "The Replace Content " + SwapCharacters(str, 'o')); } public string SwapCharacters(string strSrc, char chrSrc) { string strDst = string.Empty; try { while (strSrc.IndexOf(chrSrc) > -1) { strDst += strSrc.Substring(0, strSrc.IndexOf(chrSrc)); strDst += strSrc.Substring(strSrc.IndexOf(chrSrc) + 1, 1); strDst += chrSrc; strSrc = strSrc.Substring(strSrc.IndexOf(chrSrc) + 2); } strDst += strSrc; } catch (Exception ex) { throw ex; } return strDst; }