1

I was given a text document that has 5K+ names all in caps, and all in "double quotes." I have split all the names by the commas so I have a populated String[] filled with names in quotes. I need to remove all the quotes from the names, I have tried using .trim('"') but keep getting errors.

Here is my code:

public class NameScore {

public static void main(String[] args) throws IOException {

    //File path to name list
    String NAME_LIST = "/Users/BR/NameScores/src/p022_names.txt";


    //imports the file with names
    Scanner input = new Scanner(new File(NAME_LIST));

    //Array list that holds the appx. 5K names. Each name split by a comma
    String[] nameList = (input.nextLine()).split(",");
    //puts the list into alphabetical order.
    Arrays.sort(nameList);


    for (int i = 0; i < nameList.length; i++) {

        //nameList[i] = nameList[i].trim('"');
        System.out.println(nameList[i]);

    }
}

}

baileyr12
  • 41
  • 5
  • 1
    if this is a csv file then use something like csvReader to parse it. It can automatically get rid of double quotes – Scary Wombat Oct 28 '16 at 01:23

3 Answers3

1

You can use a regular expression with String.replaceAll(String, String) like

System.out.println(nameList[i].replaceAll("\"", ""));
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
1

As mentioned in the comments by @ScaryWombat, if this is a valid CSV file, you can use a CSV library (such as opencsv):

CSVReader reader = new CSVReader(new FileReader(".../p022_names.txt"));
List<String[]> allLines = reader.readAll();

for(String[] line: allLines){
    for(String field: line){
        System.out.print(field + "\t"); 
    }
    System.out.println();
}

CSVReader will :

  • split fields between commas;
  • remove the surrounding double quotes in each field.

opencsv's maven dependency :

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>3.7</version> 
</dependency>
alexbt
  • 14,285
  • 6
  • 67
  • 82
1

Use inputString.replaceAll("[\-\+\.\^:,]","");

For more info check it: How to remove special characters from a string?

Community
  • 1
  • 1
manmohan
  • 370
  • 2
  • 13