1

I have a sentence, which has names of an authors separated by the word "and". I want to remove the "and" and put a & instead. Is there a quick and easy way to do this. I've tried scanner and useDelimiter(), StringTokenizer, and split.

This is for example what I want to split (I am getting this information from a file on my computer):

author={J. Park and J. N. James and Q. Li and Y. Xu and W. Huang}, 

So I used:

String author = nextLine.substring(nextLine.indexOf("{") + 1, nextLine.lastIndexOf("}"));

StringTokenizer st2 = new StringTokenizer(author, " and ");

while(st2.hasMoreTokens()){
      author += st2.nextToken() + " & ";
}

The output that I get is the following:

J. Park and J. N. James and Q. Li and Y. Xu and W. HuangJ. & P & rk & J. & N. & J & mes & Q. & Li & Y. & Xu & W. & Hu & g & .

I am not entirely sure what I am doing wrong. I googled this for 2 hours last night before giving up. I have tried using "[and]", "and", "^[and]$", but with no success.

3 Answers3

1

If you just want to replace "and" with "&" you can simply call relaceAll() method on the String.

Try this.

public class Test{

    public static void main(String []args){
        String author= "J. Park and J. N. James and Q. Li and Y. Xu and W. Huang"; 
        System.out.println(author);
        author = author.replaceAll("\\band\\b", "&");
        System.out.println(author);
    }
}
Anurodh Singh
  • 814
  • 5
  • 9
1

Just for completeness, another way to do this is with replaceAll()

String author="{J. Park and J. N. James and Q. Li and Y. Xu and W. Huang}";
author = author.replaceAll( " and ", " & " );

Will get you the same result. Note the spaces around " and ". These prevent you from replacing a word like "Rosaland" with "Rosal&". The spaces around " & " are there to keep the spacing the same as before. Without them you'll get "J. Park&J. N. James".

Just FYI: "\b" is a programmers' tool. The "word boundary" it uses includes typical "programmer words". A quick check says that it matches anything that is not [A-Za-z0-9_], so if you had a name like "Johhan Fu-and-leson" it would match the "-" and replace it. Very unlikely to occur, but something to keep in mind.

Also, a string like "Lindy Harlaown_and Fate" the _ would be NOT matched and no replacement would occur. Again something to keep in mind.

Regex isn't magic and doesn't read your mind, and its default matching may not suit your particular needs.

markspace
  • 10,621
  • 3
  • 25
  • 39
1

Use the replaceAll method. For example:

String s = "J. Park and J. N. James and Q. Li and Y. Xu and W. Huang";
s = s.replaceAll("\\band\\b", "&"); // "J. Park & J. N. James & Q. Li & Y. Xu & W. Huang"

The \b word boundaries ensures that if there is a name that includes and (for example, "Band") it won't be touched.

Joni
  • 108,737
  • 14
  • 143
  • 193