convert punctuation to string

hi , i can check if a word has punctuations in it by using (!char.IsLetter( theInput[ i ] )). here the "theInput" is a string. I want to remove these punctuations, but no idea how to do it, please help


Answer this question

convert punctuation to string

  • maverick_majnoo

    that's right, you can't modify the item whilst in iteration mode :-) you may have to keep some reference of the index it is currently on or maybe have 2 instances of the same string and remove the item from it

    an example maybe:

    string theCopy = theInput

    for(int counter = 0; counter < theInput.Length; counter++)

    {

    if (Char.IsPunctuation(curChar))

    {

    theCopy = theCopy.Remove(counter, 1);

    }

    }

    theInput = theCopy;

    I'm sure there maybe a better way of doing this



  • Pierce28

    this definitely solve the problem. I also figured out a similar way of doing this, which is to declare an array which holds all the letters of "theInput", replace it with a space if any of the elements is a punctuation. then get rid of alll spaces after the loop by using "replace()", then convert the array back into "theInput" string after the loop. Anyway, your suggestion is more efficient than mineAny advanced suggestions are still welcome :)

  • techlist

    thx ahmedilyas for the quick reply. i should have said that i use a loop to go through every letter of a word to see if there is any punctuations. the code "theinput = theinput.remove(i,1)" will reduce the size of "theinput", therefore cause "index out of bounce" error. I tried to avoid this by change the code to "theinput = theinput.replace(i," "), it threw another error "can't replace "char" value with "string"plz help

  • samonwang

    Let's try something a wee bit faster:

    StringBuilder theCopy = new StringBuilder(theInput.Length);
    foreach(char curChar in theInput)
    {
    if (!Char.IsPunctuation(curChar)) // or if (Char.IsLetter(curChar))
    {
    theCopy.Append(curChar);
    }
    }
    return theCopy.ToString();
    }



  • Fuehner

    try using Char.IsPunctuation(char); (or the other overload) to see if the string contains punctuation. If so, then you need to remove it at the specified index from your example.:

    If (Char.IsPunctuation(theInput[ i ]))

    {

       theInput = theInput.Remove(i, 1);

    }

    http://msdn2.microsoft.com/en-us/library/6w3ahtyy.aspx

    is this what you maybe after



  • convert punctuation to string