-1

I am reading words from a file. I want to ignore punctuation marks with the words (for eg. if Nay, then i want to read only Nay). I have written code right now to ignore only "," from the word but my requirement is to ignore all the punctuation marks and numbers. My approach is tedious and unintelligent. Please suggest how can I ignore all the punctuation marks and numbers.

Please donot decrease my rep and block my account if you think this post is irrelevant. Let me know what else you want and I will share it with you.

One of the text files I am trying to read is as follows: Text File

I have written the code like below line to ignore ","

if(wordArray[j].charAt(k)!=',')

Please find the relevant code below

for(int k=0;k<wordArray[j].length();k++)
{
    if(wordArray[j].charAt(k)!=',' )
    {
        arrayFinal.add(wordArray[j].charAt(k));
    }
}

Updated post

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
spartan
  • 31
  • 2

2 Answers2

0

I am not sure about what exactly you want, but from your input, I gather you want this.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s = sc.next().replaceAll("[^a-zA-Z]", "");
    System.out.println(s);
}

can't --> input
cant  --> output
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

As a general programming guideline, break out large, complex methods into shorter ones. This has many benefits (unit testing, readability, extensibility, re-use).

So you can do something like:

public static String stripPunctuation(String fullString) {
    StringBuilder sb = new StringBuilder();
    for (int i=0; i < fullString.length(); i++) {
        if (Character.isLetter(fullString.charAt(i))) {
           sb.append(fullString.charAt(i));
        }
    }
    return sb.toString();
}

And call it when you need it. There are likely other third-party libraries that can do this too, but the above will not introduce dependencies.

Then your unit test method could look like:

 @Test
 public void testStripPunctuationFromString() {
      assertEquals("test", TheClassName.stripPunctuation(".*te@st45&"));
      assertEquals("", TheClassName.stripPunctuation(".#*^"));
 }
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
  • And if it's too slow for you, there are ways to speed it up: http://stackoverflow.com/questions/8894258/fastest-way-to-iterate-over-all-the-chars-in-a-string – riddle_me_this Sep 18 '14 at 06:13