Passing string by address

Hi I am trying to pass the starting and ending addresses of a string to a function:

string read = "whatever";

string newstring = Change(ref read[0], ref read[7]);
Trying to pass address of w and r for the string above to function Change

i want to do something like this:

private static void Change (ref int x, ref int y)
{
   *x = "c";
     or x = some other address location like read[2];
   
    same for y,
    *y = "c"
}

Is this possible in C#.  Thank you very much ahead of time.

   
nstefanovAsked:
Who is Participating?
 
AdGrootCommented:

You don't need the ref's before the int

private static string Change (string oldString, int x, int y)
{
            StringBuilder stringBuilder = new StringBuilder(oldString);
            char ch = stringBuilder[x];
            stringBuilder[x] = stringBuilder[y];
            stringBuilder[y] = ch;
            return stringBuilder.ToString();
}

Ad
0
 
GENTPCommented:
use the unsafe block. You might have to config it in the Project Settings. Try this


private unsafe static void Change (ref int x, ref int y)
{
   *x = "c";
     or x = some other address location like read[2];
   
    same for y,
    *y = "c"
}
0
 
AdGrootCommented:
use StringBuilder

private static string Change (string oldString, ref int x, ref int y)
{
            StringBuilder stringBuilder = new StringBuilder(oldString);
            char ch = stringBuilder[x];
            stringBuilder[x] = stringBuilder[y];
            stringBuilder[y] = ch;
            return stringBuilder.ToString();
}

Ad
0
 
nstefanovAuthor Commented:
Thanks AdGroot not exactly what I wanted but this looks like a great idea.  Will test and reward you the points if I can modify it to work.  Thanks again.

Nick
0
 
topdog770Commented:
This got me thinking..

I still tend to think to C++ like but, depending on what you're attempting to accomplish..


                  string sTest = "Michael";
                  int iStartPos = 2;
                  int iEndPos = 7;

                  string sResult = this.Change( sTest, iStartPos, iEndPos );



private string Change( string sOriginalString, int iStartPos, int iEndPos )
{
    // skipping all error checking
    string sWorkingString = sOriginalString;
    string sResultString = "";

    int iCurrentIndex = 0;
    foreach( char c in sWorkingString )
    {
        if( iCurrentIndex >= iStartPos && iCurrentIndex < iEndPos )
        {
      if( iCurrentIndex == iStartPos )
      {
            sResultString += "S";
      }
      else if( iCurrentIndex == iEndPos )
      {
           sResultString += "E";
      }
      else
      {
           sResultString += c.ToString();
      }
        }
        ++iCurrentIndex;
    }
    return sResultString;
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.