Results 1 to 19 of 19

Thread: looping thru a string to remove letters

  1. #1

    Thread Starter
    Addicted Member KingSatan's Avatar
    Join Date
    Feb 2006
    Posts
    185

    looping thru a string to remove letters

    im trying to loop thru a string one letter at a time and get rid of all letters aqnd symbols except "."

    and for some reason the string.remove(x,x) doesnt work....
    it just stays on the same letter and doesnt rip it out...


    like say i put abc123def into my pricerange textbox it would lopp over and over removing "a" but not really removing it...

    heres my code
    I'm always using
    Visual Studio 2003 c#
    I'm always working on
    web applications.

    c# Code:
    1. bool ifd;
    2. string currentchar;
    3. string deletechar;//set inside of another method as the value which goes into the database...(but this isnt the prob ill get to this later)
    4.  
    5.  
    6. public void DelChar()
    7.         {
    8.             for(int i=0; i<txtPriceRangeSpecialAddNew.Text.ToString().Length;)
    9.             {  
    10.                 if (ifd == false)
    11.                 {
    12.                     currentchar=deletechar.Substring(i,1);
    13.                     ifd=true;
    14.                 }
    15.                 else
    16.                 {
    17.                 currentchar=currentchar;
    18.                 }
    19.                 int x=0;
    20.                 try
    21.                 {
    22.                     Convert.ToInt32(currentchar);
    23.                     deletechar ="$"+deletechar+currentchar;
    24.                     x++;
    25.                 }
    26.                 catch
    27.                 {
    28.                     if (currentchar==".")
    29.                     {
    30.                         x++;
    31.                     }
    32.                     else
    33.                     {
    34.                         try
    35.                         {
    36.                             Convert.ToInt32(currentchar);
    37.                             x++;
    38.                         }
    39.                         catch
    40.                         {
    41.                         currentchar.Remove(i,1);
    42.                         }
    43.                     }
    44.                 }
    45.             }
    46.  
    47.         }

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: looping thru a string to remove letters

    Have you stepped through your code and watched the variables as you go? That's the way to understand how your code actually works.

    Having said that, all you need to do is loop through the current string and if you don't want to remove the current character then add it to a new string. Once you're done the new string will contain all the characters you want to keep.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Addicted Member KingSatan's Avatar
    Join Date
    Feb 2006
    Posts
    185

    Re: looping thru a string to remove letters

    yes
    the only thing i saw out of place was currentchar which would stay on the first letter and
    c# Code:
    1. String.Remove(x,1);
    wont remove it

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: looping thru a string to remove letters

    Have you read the documentation for String.Remove to see whether you're using it correctly? You always need to keep in mind that String objects are immutable, i.e. once you create one you cannot change it. If you need to make changes you need to create a whole new String object. That's why it would be much more efficient to simply build a new string one character at a time using a StringBuilder, rather than removing one character at a time from an existing string.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: looping thru a string to remove letters

    You look like you're trying to create a validator. Have you considered using a Regular Expression for this?

  6. #6
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Re: looping thru a string to remove letters

    currentchar = currentchar.Remove(i,1);
    I don't live here any more.

  7. #7

    Thread Starter
    Addicted Member KingSatan's Avatar
    Join Date
    Feb 2006
    Posts
    185

    Re: looping thru a string to remove letters

    i use Sting.Remove(i,1) and i got it to remove a out of "abc123def" in a string value, but it wont move on from there.

  8. #8

    Thread Starter
    Addicted Member KingSatan's Avatar
    Join Date
    Feb 2006
    Posts
    185

    Talking Re: looping thru a string to remove letters

    i got it to work


    c# Code:
    1. string deletechar;// this is the string which you assing the variable or param which is used by the textbox in the Update_button.click event
    2.         string currentchar;
    3. public void DelChar()
    4.         {
    5.             for(int i=0; i<deletechar.Length;)
    6.             {  
    7.  
    8.                     currentchar=deletechar.Substring(i,1);
    9.  
    10.                 try
    11.                 {
    12.                     Convert.ToInt32(currentchar);
    13.                     i++;
    14.                    
    15.                 }
    16.                 catch
    17.                 {
    18.                     if (currentchar==".")
    19.                     {
    20.                         i++;
    21.                     }
    22.                     else
    23.                     {
    24.                         try
    25.                         {
    26.                             Convert.ToInt32(currentchar);
    27.                             i++;
    28.                            
    29.                         }
    30.                         catch
    31.                         {
    32.                         currentchar = deletechar.Remove(i,1);
    33.                         deletechar=currentchar;
    34.                         }
    35.                     }
    36.                 }
    37.             }
    38.  
    39.         }

    the value gets tossed around like a hot potato
    currentchar = deletechar.Remove(i,1);
    deletechar=currentchar;

    the highlighted is the value of the string after the letter is removed
    and it just keeps on removing
    but i also ran into another prob on my way...
    i was using x as an int for some reason intead of i in my loop so when it reached the number it didnt remove the letters on the right side....
    Last edited by KingSatan; Apr 18th, 2007 at 12:57 PM. Reason: messed up

  9. #9

    Thread Starter
    Addicted Member KingSatan's Avatar
    Join Date
    Feb 2006
    Posts
    185

    Re: looping thru a string to remove letters

    i was wondering... is there any wildcard in c#???

    like if i were to say
    c# Code:
    1. if(deletechar==".."+wildcard){do this code;}

    or something like that....

  10. #10
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: looping thru a string to remove letters

    Code:
    string originalString = "abc12a3defa";
    char[] charsToRemove = {'a'};
    StringBuilder finalString = new StringBuilder();
    
    foreach (char ch in originalString)
    {
        if (Array.IndexOf(charsToRemove, ch) == -1)
        {
            // This is a valid character so add it to the output.
            finalString.Append(ch);
        }
    }
    
    MessageBox.Show(finalString.ToString());
    If you want to use something like a wild card then you should take penagate's advice and use a Regex.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  11. #11
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704

    Re: looping thru a string to remove letters

    I thought he wanted to remove all characters except the one specified (by the way he worded his post).

    Regardless, Array.IndexOf involves boxing... which is costly. Best to just use a byte array, you will achieve 60% more efficiency.

    Code:
    public static string RemoveAny(string source, char[] charsToRemove)
       		{
    			byte[] sourceBytes = System.Text.Encoding.Default.GetBytes(source);
    			byte[] charBytesToRemove = System.Text.Encoding.Default.GetBytes(charsToRemove);
    			byte[] tempBuffer = new byte[sourceBytes.Length];
    			int resultLength = 0;
    			bool matchFound = false;
    
    			for (int i = 0; i < sourceBytes.Length; i++)
    			{
    				matchFound = false;
    				for (int f = 0; f < charBytesToRemove.Length; f++)
    				{
    					if (sourceBytes[i] == charBytesToRemove[f])
    					{
    						matchFound = true;
    						break;
    					}
    				}
    				if (! matchFound)
    				{
    					tempBuffer[resultLength] = sourceBytes[i];
    					resultLength++;
    				}
    			}
    			return System.Text.Encoding.Default.GetString(tempBuffer,0, resultLength);
    		}
    Last edited by nemaroller; Apr 19th, 2007 at 04:15 PM. Reason: forgot the ! operator

  12. #12

    Thread Starter
    Addicted Member KingSatan's Avatar
    Join Date
    Feb 2006
    Posts
    185

    Re: looping thru a string to remove letters

    do any of you know how t oshow a dollar sign and commas (if the number is over 1000.00) without storing them in the database?

  13. #13
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704

    Re: looping thru a string to remove letters

    Code:
    double money = 1231123.12;
    Console.WriteLine(money.ToString("C"));

  14. #14

    Thread Starter
    Addicted Member KingSatan's Avatar
    Join Date
    Feb 2006
    Posts
    185

    Re: looping thru a string to remove letters

    its a c#.net 2003 web app

  15. #15
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704

    Re: looping thru a string to remove letters

    Code:
    double money = 1231123.12;
    someWebTextBox.Text = money.ToString("C");

  16. #16

    Thread Starter
    Addicted Member KingSatan's Avatar
    Join Date
    Feb 2006
    Posts
    185

    Re: looping thru a string to remove letters

    how about showing it in the datagrid without having to store the $'s and ,'s in the DB?

  17. #17
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704

    Re: looping thru a string to remove letters

    Well, depends on how your binding the data of course:
    For a bound column, you must make sure your results are returning as a double:
    Code:
    <asp:boundcolumn DataFormatString="{0:C}" DataField="amount"></asp:boundcolumn>
    If you are using a template column:
    Code:
    <asp:templatecolumn>
       <itemtemplate>
    	<%# ((double)((System.Data.DataRowView)Container.DataItem)["fieldNameofAmount"]).ToString("C") %> 
       </itemtemplate>
    </asp:templatecolumn>
    If you are handling the Datagrid.ItemDataBound event,
    then you can simply use the code in my previous post and assign it to whatever control is necessary.

    See this thread for a little more info:
    http://www.vbforums.com/showpost.php...96&postcount=4
    Last edited by nemaroller; Apr 20th, 2007 at 07:54 AM.

  18. #18

    Thread Starter
    Addicted Member KingSatan's Avatar
    Join Date
    Feb 2006
    Posts
    185

    Unhappy Re: looping thru a string to remove letters

    well i have this and it works fine but doesnt add the dollars or commas....
    which is all im really trying to do....
    but i dont want them sotered into the DB


    HTML Code:
    					</asp:TemplateColumn>
    					<asp:TemplateColumn HeaderText="Price Range">
    						<ItemTemplate>
    							<asp:Label runat="server" ID="PriceRangeS" Text='<%# ((double)((System.Data.DataRowView)Container.DataItem)["chrPriceRange"]).ToString("{0:c}") %> '>
    							</asp:Label>
    						</ItemTemplate>
    						<EditItemTemplate>
    							<asp:TextBox runat="server" ID="txtPriceRangeS" Width="104px" Text='<%# DataBinder.Eval(Container, "DataItem.chrPriceRange") %>'>
    							</asp:TextBox>
    						</EditItemTemplate>
    					</asp:TemplateColumn>


  19. #19
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: looping thru a string to remove letters

    This DataGrid currency stuff has nothing to do with the original question and should have been asked in a different thread.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

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