简体   繁体   中英

Replacing/Append multiple substrings at specific locations in a string using Java

I haven't found any solution to a specific problem I'm having. I'm doing some XML parsing in which I would like to manipulate words within a string.

Given I have a case of: 'word, word word word' - words can be any string, as I have no knowledge what they would be in advance.

I'd like to be able to manipulate the string to obtain the following outcome: 'word., word word. word' 'word., word word. word' - So, the first word and the third word I would like to append a '.' to the end of them.

What would be a suitable approach for this? Would regex be the best way?

Assuming that words will be separated using the same character(s), I think that the simplest way would be to use indexOf(" ") and then use substring methods to add a dot before the returned index. Remember that you could also use lastIndexOf(" ") for appending the dot to the third word, or you could even specify the starting position of indexOf ie

String words = "word, word word word";
String newWords

int space1 = words.indexOf(" ");

newWords = words.substring(0, space1) & "." & words.substring(space1 + 1);

int lastSpace = newWords.lastIndexOf(" ");

newWords = newWords.subString(0, lastSpace) & "." & newWords.subString(lastSpace + 1);

(I think something along those lines would work, but I haven't tested and I wrote it without an IDE)

Of course, I'm not very familiar with regex and you haven't really given that much information, so regex could potentially be an option, but I think that would require you to know the length(s) of the word(s), at the least.

If you want to use regex then the following should work for you. The regexp is broken into 3 groups which then can be referenced in the replacement regexp in replaceAll.

System.out.println("hello, my name is"
    .replaceAll("(\\w+)(,\\s*\\w+\\s+\\w+)(\\s+\\w+)", "$1.$2.$3") );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM