Replace String in occurrence using java - 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)));
}

Related

Replace the words in String without using String replace

Is there any solution on how to replace words in string without using String replace?
As you all can see this is like hard coded it. Is there any method to make it dynamically? I heard that there is some library file able to make it dynamically but I am not very sure.
Any expert out there able to give me some solutions? Thank you so much and have a nice day.
for (int i = 0; i < results.size(); ++i) {
// To remove the unwanted words in the query
test = results.toString();
String testresults = test.replace("numFound=2,start=0,docs=[","");
testresults = testresults.replace("numFound=1,start=0,docs=[","");
testresults = testresults.replace("{","");
testresults = testresults.replace("SolrDocument","");
testresults = testresults.replace("numFound=4,start=0,docs=[","");
testresults = testresults.replace("SolrDocument{", "");
testresults = testresults.replace("content=[", "");
testresults = testresults.replace("id=", "");
testresults = testresults.replace("]}]}", "");
testresults = testresults.replace("]}", "");
testresults = testresults.replace("}", "");
In this case, you will need learn regular expression and a built-in String function String.replaceAll() to capture all possible unwanted words.
For example:
test.replaceAll("SolrDocument|id=|content=\\[", "");
Simply create and use a custom String.replace() method which happens to use the String.replace() method within it:
public static String customReplace(String inputString, String replaceWith, String... stringsToReplace) {
if (inputString.equals("")) { return replaceWith; }
if (stringsToReplace.length == 0) { return inputString; }
for (int i = 0; i < stringsToReplace.length; i++) {
inputString = inputString.replace(stringsToReplace[i], replaceWith);
}
return inputString;
}
In the example method above you can supply as many strings as you like to be replaced within the stringsToReplace parameter as long as they are delimited with a comma (,). They will all be replaced with what you supply for the replaceWith parameter.
Here is an example of how it can be used:
String test = "This is a string which contains numFound=2,start=0,docs=[ crap and it may also "
+ "have numFound=1,start=0,docs=[ junk in it along with open curly bracket { and "
+ "the SolrDocument word which might also have ]}]} other crap in there too.";
testResult = customReplace(strg, "", "numFound=2,start=0,docs=[ ", "numFound=1,start=0,docs=[ ",
+ "{ ", "SolrDocument ", "]}]} ");
System.out.println(testResult);
You can also pass a single String Array which contains all your unwanted strings within its elements and pass that array to the stringsToReplace parameter, for example:
String test = "This is a string which contains numFound=2,start=0,docs=[ crap and it may also "
+ "have numFound=1,start=0,docs=[ junk in it along with open curly bracket { and "
+ "the SolrDocument word which might also have ]}]} other crap in there too.";
String[] unwantedStrings = {"numFound=2,start=0,docs=[ ", "numFound=1,start=0,docs=[ ",
"{ ", "SolrDocument ", "]}]} "};
String testResult = customReplace(test, "", unwantedStrings);
System.out.println(testResult);

String Parsing in Java and android

I want to parse the data below in java. What approach shall I follow?
I want to neglect ; inside { }.
Thus Version, Content, Provide, UserConfig and Icon as name and corresponding values.
Version:"1";
Content:2013091801;
Provide:"Airtel";
UserConfig :
{
Checksum = "sha1-234448e7e573b6dedd65f50a2da72245fd3b";
Source = "content\\user.ini";
};
Icon:
{
Checksum = "sha1-a99f835tytytyt3177674489770e613c89390a8c4";
Source = "content\\resept_ico.bmp";
};
Here we can't use String.split(";") function.
It would have been lot more complex to convert using the Regex and then creating a method to extract the required fields,
What I did was converted the above mentioned input to Json compatible string and then used GSON library by google to parse the String to my customized class,
class MyVer
{
String Version;
long Content;
String Provide;
Config UserConfig;
Config Icon;
String Source;
}
class Config
{
String Checksum;
String Source;
}
public static void main(String[] args)
{
String s = "Version:\"1\";Content:2013091801;Provide:\"Airtel\";UserConfig :{ Checksum = \"sha1-234448e7e573b6dedd65f50a2da72245fd3b\"; Source = \"content\\user.ini\";};Icon:{ Checksum = \"sha1-a99f835tytytyt3177674489770e613c89390a8c4\"; Source = \"content\\resept_ico.bmp\";};";
String startingBracePattern = Pattern.quote("{");
String endBracePattern = Pattern.quote("}");
s=s.replaceAll(Pattern.quote("\\"), "\\\\\\\\"); //Replacing all the single \ with double \\
s = s.replaceAll("\\s*"+startingBracePattern +"\\s*", "\\{\""); //Replacing all the `spaces { spaces` with `{"` MEANS all the { to replace with {"
s = s.replaceAll(";\\s*"+endBracePattern +"\\s*;", "\\};"); //Replacing all the `; spaces } spaces ;` with `},"` MEANS all the ;}; to replace with };
s = "{\"" + s.substring(0, s.length() - 1) +"}"; //Removing last ; and appending {" and }
s = s.replaceAll("\\s*:", "\":"); // Replacing all the `space with :` with `":`
s = s.replaceAll("\\s*;\\s*", ",\""); //Replacing all the `spaces ; spaces` with `,"`
s = s.replaceAll("\\s*=\\s*", "\":"); //Replacing all the `spaces = spaces` with `":`
Gson gson = new Gson();
MyVer newObj = gson.fromJson(s, MyVer.class);
}
This converts and give you the object of MyVer and then you can access all the variables.
NOTE: You can alter the code little to replace all \r\n if they are present in your input variables. I have not used them and your actual data supplied in question in a single line for simplicity.
JSON sounds a lot easier in this case..
.. however, if you were to do this using regular expressions, one way would be:
for the simple cases (eg. version):
// look for Version: some stuff ;
Pattern versionPattern = Pattern.compile("Version\\s*:\\s*\"\\w+\"\\s*;");
// the whole big string you're looking in
String bigString = ...; // the entire string from before can go here
// create a matcher for the "version pattern"
Matcher versionMatcher = versionPattern.matcher(bigString);
// check if there's a match in the string
if(versionMatcher.find()) {
// get the matching substring
String matchingSubstring = bigString.substring(
versionMatcher.start(),
versionMatcher.end()
);
// we need the area between the quotes
String version = matchingSubstring.split("\"")[1];
// do something with it
...
}
for the harder (multi-line) cases (eg. UserConfig):
// look for UserConfig : { some stuff };
Pattern userconfigPattern = Pattern.compile("UserConfig\\s*:\\s*{[^}]*};", Pattern.DOTALL);
// create a matcher for the "user config pattern"
Matcher userconfigMatcher = userconfigPattern.matcher(bigString);
// check if there's a match in the string
if(userconfigMatcher.find()) {
// get the matching substring
String matchingSubstring = bigString.substring(
userconfigMatcher.start(),
userconfigMatcher.end()
);
// we need the area between the curly braces
String version = matchingSubstring.split("[{}]")[1];
// do something with it
...
}
EDIT: this is probably an easier way
// split the input string into fields
String[] fields = bigString.split("[^:]+:([^{;]+;)|({[^}]+};)");
// for each key-value pair
for(String field : fields) {
// the key and value are separated by colons
String parts = field.split(":");
String key = parts[0];
String value = parts[1];
// do something with them, or add them to a map
...
}
This last way splits the input string based on the assumption that each key-value pair consists of:
some (non-colon) characters at the start, followed by
a colon,
either
-> some characters that are not curly braces or semi-colons (for simple attributes), or
-> curly braces containing some characters that are not curly braces
a semi-colon
Here is json solution
str = "{" + str.substring(0, str.lastIndexOf(";")).replace(";\n}", "}") + "}";
try {
JSONObject json = new JSONObject(str);
String version = json.getString("Version");
JSONObject config = json.getJSONObject("UserConfig");
String source = config.getString("Source");
} catch (JSONException e) {
e.printStackTrace();
}
since ";" should not be in front of "}"
Source = "content\\resept_ico.bmp";
}
we need remove them

String modification in 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.

Android - Editing my String so each word starts with a capital

I was wondering if someone could provide me some code or point me towards a tutrial which explain how I can convert my string so that each word begins with a capital.
I would also like to convert a different string in italics.
Basically, what my app is doing is getting data from several EditText boxes and then on a button click is being pushed onto the next page via intent and being concatenated into 1 paragraph. Therefore, I assume I need to edit my string on the intial page and make sure it is passed through in the same format.
Thanks in advance
You can use Apache StringUtils. The capitalize method will do the work.
For eg:
WordUtils.capitalize("i am FINE") = "I Am FINE"
or
WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
Here is a simple function
public static String capEachWord(String source){
String result = "";
String[] splitString = source.split(" ");
for(String target : splitString){
result
+= Character.toUpperCase(target.charAt(0))
+ target.substring(1) + " ";
}
return result.trim();
}
The easiest way to do this is using simple Java built-in functions.
Try something like the following (method names may not be exactly right, doing it off the top of my head):
String label = Capitalize("this is my test string");
public String Capitalize(String testString)
{
String[] brokenString = testString.split(" ");
String newString = "";
for(String s : brokenString)
{
s.charAt(0) = s.charAt(0).toUpper();
newString += s + " ";
}
return newString;
}
Give this a try, let me know if it works for you.
Just add android:inputType="textCapWords" to your EditText in layout xml. This wll make all the words start with the Caps letter.
Strings are immutable in Java, and String.charAt returns a value, not a reference that you can set (like in C++). Pheonixblade9's will not compile. This does what Pheonixblade9 suggests, except it compiles.
public String capitalize(String testString) {
String[] brokenString = testString.split(" ");
String newString = "";
for (String s : brokenString) {
char[] chars = s.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
newString = newString + new String(chars) + " ";
}
//the trim removes trailing whitespace
return newString.trim();
}
String source = "hello good old world";
StringBuilder res = new StringBuilder();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print("Result: " + res.toString().trim());

Problem replacing a String in Java

I am trying to replace a URL with a shortened URL inside of a String:
public void shortenMessage()
{
String body = composeEditText.getText().toString();
String shortenedBody = new String();
String [] tokens = body.split("\\s");
// Attempt to convert each item into an URL.
for( String token : tokens )
{
try
{
Url url = as("mycompany", "someapikey").call(shorten(token));
Log.d("SHORTENED", token + " was shortened!");
shortenedBody = body.replace(token, url.getShortUrl());
}
catch(BitlyException e)
{
//Log.d("BitlyException", token + " could not be shortened!");
}
}
composeEditText.setText(shortenedBody);
// url.getShortUrl() -> http://bit.ly/fB05
}
After the links are shortened, I want to print the modified string in an EditText. My EditText is not displaying my messages properly.
For example:
"I like www.google.com" should be "I like [some shortened url]" after my code executes.
In Java, strings are immutable. String.replace() returns a new string which is the result of the replacement. Thus, when you do shortenedBody = body.replace(token, url.getShortUrl()); in a loop, shortenedBody will hold the result of (only the very) last replace.
Here's a fix, using StringBuilder.
public void shortenMessage()
{
String body = composeEditText.getText().toString();
StringBuilder shortenedBody = new StringBuilder();
String [] tokens = body.split("\\s");
// Attempt to convert each item into an URL.
for( String token : tokens )
{
try
{
Url url = as("mycompany", "someapikey").call(shorten(token));
Log.d("SHORTENED", token + " was shortened!");
shortenedBody.append(url.getShortUrl()).append(" ");
}
catch(BitlyException e)
{
//Log.d("BitlyException", token + " could not be shortened!");
}
}
composeEditText.setText(shortenedBody.toString());
// url.getShortUrl() -> http://bit.ly/fB05
}
You'll probably want String.replaceAll and Pattern.quote to "quote" your string before you pass it to replaceAll, which expects a regex.

Categories