Tuesday, September 27, 2011

Replace character based on specific index

Here's an example snippet that will replace a character
based from a specific index.
Source: DreamInCode
To use it in your program do it like this:
Code:
  // Replaces a character in a string with the character specified.  
  void replaceCharWithChar(ref string text, int index, char charToUse)  
  {  
    char[] tmpBuffer = text.ToCharArray();  
    buffer[index] = charToUse;  
    text = new string(tmpBuffer);  
  }  

  //IN YOUR MAIN MODULE/FUNCTION.  
  //money has comma, example: $2,000, 4 BR, 180 m²   
  //LandPriceBedroom = "$120, 2 BR, 90 m²";  
  //IF COMMA OCCURS MORE THAN TWO, REPLACE THE FIRST  
  //COMMA WITH SPACE. SINCE IT COULD BE A MONEY W/  
  //THOUSANDS SEPARATOR  
  if (LandPriceBedroom.Split(',').Length > 3)   
  {  
    int firstIndexComma = LandPriceBedroom.IndexOf(",");  
    replaceCharWithChar(ref LandPriceBedroom, firstIndexComma, ' ');  
  }

0 comments:

Post a Comment