String modification in java - java

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();
}
}
}

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

You can do it in two steps:
To get all the words from the string before "-", you can use String
substring and indexOf methods.
To replace empty spaces with hiphen(-), you can use the String 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);

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();
}
}
}

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] + "-";

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.

Related

Change all letters except space from a string using Java

I want to change all letters from a string to "-" char except space using Java.
I tried:
String out = secretWord.replaceAll("^ " , "-");
and
String out = secretWord.replaceAll("\\s" , "-");
They didn't work.
I tried:
String newWord = secretWord.replaceAll("[A-Z]" , "-");
It worked but i didn't change Turkish characters I use in that string.
Original Code:
public class ChangeToLine {
public static void main(String[] args) {
String originalWord = "ABİDİKUŞ GUBİDİKUŞ";
String secretWord = originalWord;
}
}
You can use the \\S regex:
String s = "Sonra görüşürüz";
String replaced = s.replaceAll("\\S", "-");
System.out.println(replaced); // outputs ----- ---------
Use a character class
String out = secretWord.replaceAll("[^ ]" , "-");
or a capital S, instead of a lower s to replace all non space chars
String out2 = secretWord.replaceAll("\\S" , "-");
NOT needs to be expressed in square brackets in java.util.regex.Pattern:
String out = secretWord.replaceAll("[^\\s]", "-")

Replace String in occurrence using java

I have a string which needs to be replaced by occurrence
My Code:
String value="EMPID,NAME,AGE,ADDRESS,PROJECT,DOMAIN,Work Item $WORKNUMBER$ is assigned to $ASSIGNEDTO$ due to $REASON$,~WORKNUMBER~ASSIGNEDTO~REASON~"
String[] value_split = value.split("\\,");
System.out.println(value_split[6]);
String template=value_split[6];
String var=value_split[7];
String[] bindvar=var.split("~");
String finaltemplate="";
for (String string : bindvar) {
//System.out.println(string);
String valuefromQueue=getQueueLog(string);
//System.out.println(valuefromQueue);
System.out.println(template.replace("$",valuefromQueue ));
}
public static String getQueueLog(String var) {
String resval ="";
if (var == null) {
return var;
}
switch (var) {
case "WORKNUMBER":
resval = "12123123";
break;
case "ASSIGNEDTO":
resval = "RM";
break;
case "REASON":
resval = "NEW LC";
break;
}
return resval;
}
What I get in String template =Work Item $WORKNUMBER$ is assigned to $ASSIGNEDTO$ due to $REASON$
And in valuefromQueue=12123123 RM NEWLC
Expected Output should be :Work Item 12123123 is assigned to RM due to NEWLC
My output:
Work Item 12123123WORKNUMBER12123123 is assigned to 12123123ASSIGNEDTO12123123 due to 12123123REASON12123123
You replace isn't good, your template is $keyWord$, so template.replace("$"+string+"$",valuefromQueue )
`template.replace("$", valuefromQueue)`
You are replacing all occurrences of $. Those appear as pre- and postfix of all your placeholders ($WORKNUMBER$). The output is exactly what I would expect.
To get the output you desire, you need to specify the exact placeholders, like so:
`template.replace("$WORKNUMBER$", valuefromQueue)`
Looking at your getQueueLog() method, it looks as if string contains the placeholder strings (WORKNUMBER, ASSIGNEDTO and REASON) without the dollar signs. Hence, you should be able to use that for replace():
`template.replace("$" + string + "$", valuefromQueue)`
Note: Since you don't seem to be using valuefromQueue anywhere else, you can shorten this:
for (String string : bindvar) {
String valuefromQueue=getQueueLog(string);
System.out.println(template.replace("$" + string + "$", valuefromQueue));
}
... to this:
for (String string : bindvar) {
System.out.println(template.replace("$" + string + "$", getQueueLog(string)));
}

Remove all words starting with "http" in a string?

I simply want to replace all words starting with "http" and ends with space or "\n" in a string
Example string is.
Full results below;
http://www.google.com/abc.jpg is a url of an image.
or some time it comes like https://www.youtube.com/watch?v=9Xwhatever this is an example text
Result of the string should be like
is a url of an image.
or some time it comes like this is an example text
I simply want to replace it with ""; i know the logic but don't know the function.
My logic is
string.startwith("http","\n")// starts with http and ends on next line or space
.replaceAll("")
public static void main(String[] args) {
String s = "https://www.google.com/abc.jpg is a url of an image.";
System.out.println(s.replaceAll("https?://.*?\\s+", ""));
}
O/P :
is a url of an image.
String.replaceAll() allows you to use a regex. In a regex, ^ allows you to capture the beginning of the String. Hence, you can do like that :
System.out.print("http://google-http".replaceAll("^http", ""));
result:
://google-http
The http at the beginning has be removed but not the one at the end.
public static void main(String[] args) {
String str = "https://www.google.com/abc.jpg is a url of an image.";
String subStr1 = "http://";
String substr2 = "https://";
String foundStr = "";
if(str.startsWith(subStr1)) {
foundStr = subStr1;
}
if (str.startsWith(subStr2)) {
foundStr = subStr2;
}
str = str.replaceAll(foundStr, "");
str = str.replaceAll(" ", "");
}

How to replace or convert the first occurrence of a dot from a string in java

Example:
Input
Str = P.O.Box
Output
Str= PO BOX
I can able to convert the string to uppercase and replace all dot(.) with a space.
public static void main(String args[]){
String s = "P.O.Box 1836";
String uppercase = s.toUpperCase();
System.out.println("uppercase "+uppercase);
String replace = uppercase.replace("."," ");
System.out.println("replace "+replace);
}
System.out.print(s.toUpperCase().replaceFirst("[.]", "").replaceAll("[.]"," "));
If you look the String API carefully, you would notice that there's a methods that goes by:-
replaceFirst(String regex, String replacement)
Hope it helps.
You have to use the replaceFirst method twice. First for replacing the . with <nothing>. Second for replacing the second . with a <space>.
String str = "P.O.Box";
str = str.replaceFirst("[.]", "");
System.out.println(str.replaceFirst("[.]", " "));
This one liner should do the job:
String s = "P.O.Box";
String replace = s.toUpperCase().replaceAll("\\.(?=[^.]*\\.)", "").replace('.', ' ');
//=> PO BOX
String resultValue = "";
String[] result = uppercase.split("[.]");
for (String value : result)
{
if (value.toCharArray().length > 1)
{
resultValue = resultValue + " " + value;
}
else
{
resultValue = resultValue + value;
}
}
Try this
System.out.println("P.O.Box".toUpperCase().replaceFirst("\\.","").replaceAll("\\."," "));
Out put
PO BOX
NOTE: \\ is needed here if you just use . only your out put will blank.
Live demo.
You should use replaceFirst method twice.
String replace = uppercase.replace("\\.", "").replaceFirst("\\.", "");
As you want to remove the first dot and replace the second one with a space, you need replace the whole P.O. section
Use
replace("P\\.O\\.", "PO ");

Tokenize a string with a space in java

I want to tokenize a string like this
String line = "a=b c='123 456' d=777 e='uij yyy'";
I cannot split based like this
String [] words = line.split(" ");
Any idea how can I split so that I get tokens like
a=b
c='123 456'
d=777
e='uij yyy';
The simplest way to do this is by hand implementing a simple finite state machine. In other words, process the string a character at a time:
When you hit a space, break off a token;
When you hit a quote keep getting characters until you hit another quote.
Depending on the formatting of your original string, you should be able to use a regular expression as a parameter to the java "split" method: Click here for an example.
The example doesn't use the regular expression that you would need for this task though.
You can also use this SO thread as a guideline (although it's in PHP) which does something very close to what you need. Manipulating that slightly might do the trick (although having quotes be part of the output or not may cause some issues). Keep in mind that regex is very similar in most languages.
Edit: going too much further into this type of task may be ahead of the capabilities of regex, so you may need to create a simple parser.
line.split(" (?=[a-z+]=)")
correctly gives:
a=b
c='123 456'
d=777
e='uij yyy'
Make sure you adapt the [a-z+] part in case your keys structure changes.
Edit: this solution can fail miserably if there is a "=" character in the value part of the pair.
StreamTokenizer can help, although it is easiest to set up to break on '=', as it will always break at the start of a quoted string:
String s = "Ta=b c='123 456' d=777 e='uij yyy'";
StreamTokenizer st = new StreamTokenizer(new StringReader(s));
st.ordinaryChars('0', '9');
st.wordChars('0', '9');
while (st.nextToken() != StreamTokenizer.TT_EOF) {
switch (st.ttype) {
case StreamTokenizer.TT_NUMBER:
System.out.println(st.nval);
break;
case StreamTokenizer.TT_WORD:
System.out.println(st.sval);
break;
case '=':
System.out.println("=");
break;
default:
System.out.println(st.sval);
}
}
outputs
Ta
=
b
c
=
123 456
d
=
777
e
=
uij yyy
If you leave out the two lines that convert numeric characters to alpha, then you get d=777.0, which might be useful to you.
Assumptions:
Your variable name ('a' in the assignment 'a=b') can be of length 1 or more
Your variable name ('a' in the assignment 'a=b') can not contain the space character, anything else is fine.
Validation of your input is not required (input assumed to be in valid a=b format)
This works fine for me.
Input:
a=b abc='123 456' &=777 #='uij yyy' ABC='slk slk' 123sdkljhSDFjflsakd#*#&=456sldSLKD)#(
Output:
a=b
abc='123 456'
&=777
#='uij yyy'
ABC='slk slk'
123sdkljhSDFjflsakd#*#&=456sldSLKD)#(
Code:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
// SPACE CHARACTER followed by
// sequence of non-space characters of 1 or more followed by
// first occuring EQUALS CHARACTER
final static String regex = " [^ ]+?=";
// static pattern defined outside so that you don't have to compile it
// for each method call
static final Pattern p = Pattern.compile(regex);
public static List<String> tokenize(String input, Pattern p){
input = input.trim(); // this is important for "last token case"
// see end of method
Matcher m = p.matcher(input);
ArrayList<String> tokens = new ArrayList<String>();
int beginIndex=0;
while(m.find()){
int endIndex = m.start();
tokens.add(input.substring(beginIndex, endIndex));
beginIndex = endIndex+1;
}
// LAST TOKEN CASE
//add last token
tokens.add(input.substring(beginIndex));
return tokens;
}
private static void println(List<String> tokens) {
for(String token:tokens){
System.out.println(token);
}
}
public static void main(String args[]){
String test = "a=b " +
"abc='123 456' " +
"&=777 " +
"#='uij yyy' " +
"ABC='slk slk' " +
"123sdkljhSDFjflsakd#*#&=456sldSLKD)#(";
List<String> tokens = RegexTest.tokenize(test, p);
println(tokens);
}
}
Or, with a regex for tokenizing, and a little state machine that just adds the key/val to a map:
String line = "a = b c='123 456' d=777 e = 'uij yyy'";
Map<String,String> keyval = new HashMap<String,String>();
String state = "key";
Matcher m = Pattern.compile("(=|'[^']*?'|[^\\s=]+)").matcher(line);
String key = null;
while (m.find()) {
String found = m.group();
if (state.equals("key")) {
if (found.equals("=") || found.startsWith("'"))
{ System.err.println ("ERROR"); }
else { key = found; state = "equals"; }
} else if (state.equals("equals")) {
if (! found.equals("=")) { System.err.println ("ERROR"); }
else { state = "value"; }
} else if (state.equals("value")) {
if (key == null) { System.err.println ("ERROR"); }
else {
if (found.startsWith("'"))
found = found.substring(1,found.length()-1);
keyval.put (key, found);
key = null;
state = "key";
}
}
}
if (! state.equals("key")) { System.err.println ("ERROR"); }
System.out.println ("map: " + keyval);
prints out
map: {d=777, e=uij yyy, c=123 456, a=b}
It does some basic error checking, and takes the quotes off the values.
This solution is both general and compact (it is effectively the regex version of cletus' answer):
String line = "a=b c='123 456' d=777 e='uij yyy'";
Matcher m = Pattern.compile("('[^']*?'|\\S)+").matcher(line);
while (m.find()) {
System.out.println(m.group()); // or whatever you want to do
}
In other words, find all runs of characters that are combinations of quoted strings or non-space characters; nested quotes are not supported (there is no escape character).
public static void main(String[] args) {
String token;
String value="";
HashMap<String, String> attributes = new HashMap<String, String>();
String line = "a=b c='123 456' d=777 e='uij yyy'";
StringTokenizer tokenizer = new StringTokenizer(line," ");
while(tokenizer.hasMoreTokens()){
token = tokenizer.nextToken();
value = token.contains("'") ? value + " " + token : token ;
if(!value.contains("'") || value.endsWith("'")) {
//Split the strings and get variables into hashmap
attributes.put(value.split("=")[0].trim(),value.split("=")[1]);
value ="";
}
}
System.out.println(attributes);
}
output:
{d=777, a=b, e='uij yyy', c='123 456'}
In this case continuous space will be truncated to single space in the value.
here attributed hashmap contains the values
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("<file name>")));
while (s.hasNext()) {
System.out.println(s.next());
<write for output file>
}
} finally {
if (s != null) {
s.close();
}
}
}
}
java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(line, " ");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
int index = token.indexOf('=');
String key = token.substring(0, index);
String value = token.substring(index + 1);
}
Have you tried splitting by '=' and creating a token out of each pair of the resulting array?

Categories