Results 1 to 4 of 4

Thread: Cleaning a string

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Nov 2001
    Location
    Yewston, Texis
    Posts
    240

    Cleaning a string

    I'm reading in a string from a database, but there are non-printing characters that are being read in that cause problems elsewhere.

    I thought it was just a newline, but the following didn't work:

    string theString = "junk read in from database";
    theString.Replace("\n", "");

    //This didn't work either:
    theString.Replace(Environment.NewLine, "");

    Since those don't work, I can only assume that there are other types of characters in the string. Is there a simple way to fix the string, or do I just need to write a loop going through the string one character at a time? What about regexp?

    cudabean

  2. #2
    Sleep mode
    Join Date
    Aug 2002
    Location
    RUH
    Posts
    8,083
    So you want to replace white spaces with newline chars ? If so , then try this :

    PHP Code:
    string theString "junk read in from database";
    theString =theString.Replace(" ",Environment.NewLine); 

  3. #3
    Frenzied Member
    Join Date
    Aug 2000
    Location
    Birmingham, AL
    Posts
    1,276
    You may need to replace carriage returns and line feeds both.
    Code:
    theString.Replace("\r", "");
    theString.Replace("\n", "");

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Nov 2001
    Location
    Yewston, Texis
    Posts
    240
    Thanks all responders. I found this did the job nicely:

    Code:
    public static String filter(String userInput) 
    		{
    			Regex re = new Regex("([^A-Za-z0-9@.' _-]+)");
    			String filtered = re.Replace(userInput, "");
    			return filtered;
    		}
    It get's rid of more than just any non-printing character, but that was OK in this instance. The regular expression above only allows the character ranges that are listed and kills everything else.

    cudabean

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width