I have a String and list of words. I want to search the each word in that string and replace that word with any shortcut like UPDATE DATABASE to UPD DB.
Below are the list of words I need to look for
ALTER DATABASE, ALTER TABLE, ALTER VIEW, CREATE DATABASE, CREATE PROCEDURE, CREATE SCHEMA, CREATE TABLE, CREATE VIEW, DELETE FROM, DROP DATABASE, DROP PROCEDURE, DROP TABLE, DROP VIEW, UPDATE DATABASE.
I used if else if condition but I don't think that is a efficient way to code. Can any one please help me in this issue. I asked my friends about this they told me to use REGEX but I feel regex is complex for me to understand.
Make sure to use replaceAll(). Also you could put all of the terms and replacements in an array.
Like so:
String text = "ALTER DATABASE, ALTER TABLE, ALTER VIEW, CREATE DATABASE, CREATE PROCEDURE, CREATE SCHEMA, CREATE TABLE";
String[] terms = {ALTER DATABASE, ALTER TABLE, ALTER VIEW, CREATE DATABASE, CREATE PROCEDURE, CREATE SCHEMA, CREATE TABLE};
String[] replaceWith = {"","","","","","",""}; // whatever you replace with
for(int i = 0; i < terms; i++) {
// may want to account for uppercase/lower case here too
text = text.replaceAll(terms[i],replaceWith[i]);
}
نصائح أخرى
I might not have understood your question well but...
The String class in Java offers a "replace" method, use: