Reputation: 63
Hi i am having string like " MOTOR PRIVATE CAR-PACKAGE POLICY " . Now i want remove last two words and add hyphen between words finally i want string like " MOTOR-PRIVATE-CAR' . I tried many times using string methods in java but could not find exactly. Can anyone give a solution for that . Give me a code is plus for me.
Thanks in advance
public class StringModify {
public static void main(String[] args) {
try {
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
System.out.println("Value-------------------->"+value.replaceFirst("\\s*\\w+\\s+\\w+$", ""));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 1456
Reputation: 19
String var = "/"; String query = "INSERT INTO Recieptnumbersetup VALUES('"+Prestring+"' '"+var+"','"+var+"' '"+post string+"')" ;
PS = connection.PrepareStatement(query);
Use this i have used slash over here i was having same problem.
Upvotes: 0
Reputation: 17622
You can do it with the help of substring()
and replaceAll()
methods
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
value = value.substring(0, value.indexOf("-")); //get the string till -
value = value.replaceAll("\\s", "-"); //replace all the space chars with -
System.out.println(value);
I have used String.replaceAll()
instead of String.replace()
to use the regex for white space
\s
stands for white space character and and while adding it as regex, we need to escape it with an extra \
so --> \\s
indexOf("-")
method returns the index of first occurrence of the String passed, which should be the 2nd parameter to substring
method, which is the endIndex
Upvotes: 8
Reputation: 1352
You can split the string with '-'
which gives you the part of the string in which you need to insert ' '
. Split the string again with ' '
and insert '-'
b/w the words.
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
String[] phrase = value.split("-");
String[] words = phrase[0].split(" ");
String newValue;
for(int i = 0; i < words.length; i++)
newValue += words[i] + "-";
Upvotes: 0
Reputation: 691
public class StringModify {
/**
* @param args
*/
public static void main(String[] args) {
try {
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
System.out.println("Value-------------------->"+value.replaceFirst("\\s*\\w+\\s+\\w+$", ""));
value = value.substring(0,value.indexOf("-")); // get the words before "-"
value = value.replace(" ", "-"); // replace space with hiphen
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Upvotes: 1
Reputation: 68715
You can do it in two steps:
substring
and indexOf
methods.replace
method.Here is the code:
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
value = value.substring(0,value.indexOf("-")); // get the words before "-"
value = value.replace(" ", "-"); // replace space with hiphen
System.out.println(value);
Upvotes: 1