I can already tell this is a stupid question, but I'm trying to login to a web page using postUrl() and when I explicitly write the post data like this:
String postData = "username=johndoe&password=mypassword";
myWebview.postUrl("https://moodle.domain.com/login/index.php", postData.getBytes());
It works, but if I construct the postData using variables:
String postData = "username="+user+"&password="+pass;
myWebview.postUrl("https://moodle.domain.com/login/index.php", postData.getBytes());
It doesn't work. Wrong credentials. I've verified that both strings have the exact same value and I tried using UTF-8.
I just don't understand, this doesn't make any sense.
It look Like, the 'user' or the 'pass' has invisible symbols. You need:
1) Check string using equals:
String postData1 = "username=johndoe&password=mypassword";
String postData2 = "username="+user+"&password="+pass;
System.out.println(postData1.equals(postData2));
2) Try to find invisible symbols, for example:
String postData1 = "username=johndoe&password=mypassword";
String postData2 = "username="+user+"&password="+pass;
char[] arr1 = postData1.toCharArray();
char[] arr2 = postData1.toCharArray();
for (int i=0; i< Math.max(arr1.length(), arr2.length(); i++ ) {
if(arr1[i] != arr2[i]) {
System.out.println("Different i " + i);
}
}
Try the below
String postData = "username=" + URLEncoder.encode(my_username, "UTF-8") + "&password=" + URLEncoder.encode(my_password, "UTF-8");
webview.postUrl("https://moodle.domain.com/login/index.php",postData.getBytes());
Related
String can be like below. Using java1.6
String example = "<number>;<name-value>;<name-value>";
String abc = "+17005554141;qwq=1234;ddd=ewew;otg=383";
String abc = "+17005554141;qwq=123454";
String abc = "+17005554141";
I want to remove qwq=1234 if present from String. qwq is fixed and its value can VARY like for ex 1234 or 12345 etc
expected result :
String abc = "+17005554141;ddd=ewew;otg=383";
String abc = "+17005554141"; \\removed ;qwq=123454
String abc = "+17005554141";
I tried through
abc = abc.replaceAll(";qwq=.*;", "");
but not working.
I came up with this qwq=\d*\;? and it works. It matches for 0 or more decimals after qwq=. It also has an optional parameter ; since your example seems to include that this is not always appended after the number.
I know the question is not about javascript, but here's an example where you can see the regex working:
const regex = /qwq=\d*\;?/g;
var items = ["+17005554141;qwq=123454",
"+17005554141",
"+17005554141;qwq=1234;ddd=ewew;otg=383"];
for(let i = 0; i < items.length; i++) {
console.log("Item before replace: " + items[i]);
console.log("Item after replace: " + items[i].replace(regex, "") + "\n\n");
}
You can use regex for removing that kind of string like this. Use this code,
String example = "+17005554141;qwq=1234;ddd=ewew;otg=383";
System.out.println("Before: " + example);
System.out.println("After: " + example.replaceAll("qwq=\\d+;?", ""));
This gives following output,
Before: +17005554141;qwq=1234;ddd=ewew;otg=383
After: +17005554141;ddd=ewew;otg=383
.* applies to multi-characters, not limited to digits. Use something that applies only to bunch of digits
abc.replaceAll(";qwq=\\d+", "")
^^
Any Number
please try
abc = abc.replaceAll("qwq=[0-9]*;", "");
If you don't care about too much convenience, you can achieve this by just plain simple String operations (indexOf, replace and substring). This is maybe the most legacy way to do this:
private static String replaceQWQ(String target)
{
if (target.indexOf("qwq=") != -1) {
if (target.indexOf(';', target.indexOf("qwq=")) != -1) {
String replace =
target.substring(target.indexOf("qwq="), target.indexOf(';', target.indexOf("qwq=")) + 1);
target = target.replace(replace, "");
} else {
target = target.substring(0, target.indexOf("qwq=") - 1);
}
}
return target;
}
Small test:
String abc = "+17005554141;qwq=1234;ddd=ewew;otg=383";
String def = "+17005554141;qwq=1234";
System.out.println(replaceQWQ(abc));
System.out.println(replaceQWQ(def));
outputs:
+17005554141;ddd=ewew;otg=383
+17005554141
Another one:
abc.replaceAll(";qwq=[^;]*;", ";");
You must to use groups in replaceAll method.
Here is an example:
abc.replaceAll("(.*;)(qwq=\\d*;)(.*)", "$1$3");
More about groups you can find on: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
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);
I'm looking for an efficient (one line) string manipulation code to achieve this, regex probably.
I have a string, for example, "Calvin" and I need to convert this to "/C/a/l/Calvin".
i.e. take first three characters, separate them using '/' and later append the original string.
This is the code I've come up with and its working fine, just looking for a better one.
String first = StringUtils.substring(prodName, 0, 1);
String second = StringUtils.substring(prodName, 1, 2);
String third = StringUtils.substring(prodName, 2, 3);
String prodPath = path + "/" + first + "/" + second + "/" + third + "/" + prodName + "/" ;
prodName.replaceAll("^(.)(.)(.).*", "/$1/$2/$3/$0")
What is the point of StringUtils.substring(prodName, 0, 1) when the built-in prodName.substring(0, 1) will do the same thing??
Anyway, assuming prodName is always at least 3 characters long (since you didn't give rules for expected output if it is not), this is the fastest way to do it:
String prodPath = path + '/' +
prodName.charAt(0) + '/' +
prodName.charAt(1) + '/' +
prodName.charAt(2) + '/' +
prodName + '/';
Normally, char + char is integer addition, not string concatenation, but since the first value is a String, and the + operator is left-associative, all + operators are string concatenations, not numeric additions.
How about using String.charAt
StringBuilder b = new StringBuilder (path);
b.append ('/').append (prodName.charAt (0))
.append ('/').append(prodName.charAt (1))
.append ('/').append(prodName.charAt (2))
.append ('/').append (prodName).append ('/');
Don't use regex for simple stuff like this. You may save a couple lines, but you loose a lot in readability. Regex usually take some time to understand when reading them.
String s = path;
for (int i = 0; i < 3; i++)
s += prodName.substring(i,i+1) + "/";
s += prodName
You can use MessageFormat.format()
MessageFormat.format("{0}/{1}/{2}/{3}/{4}/", baseDir, name.charAt(0), name.charAt(1), name.charAt(2), name);
imho i would wrap it for readability,
private String getProductionDirectoryPath(String baseDir, String name) {
return MessageFormat.format("{0}/{1}/{2}/{3}/{4}/", baseDir, name.charAt(0), name.charAt(1), name.charAt(2), name);
}
Positive look ahead can be used
public static void main(String[] args) {
String s = "Calvin";
System.out.println(s.replaceAll("(?=^(\\w)(\\w)(\\w))", "/$1/$2/$3/"));
}
O/P:
/C/a/l/Calvin
No use of a regex, but a simple split over nothing =)
String[] firstThree = prodName.split("");
String prodPath = path + "/" + firstThree[0] + "/" + firstThree[1] + "/" + firstThree[2] + "/" + prodName + "/";
Another approach is using charAt():
String prodPath = path + "/" + prodName.charAt(0) + "/" + prodName.charAt(1) + "/"+ prodName.charAt(2) + "/" + prodName + "/";
You said efficient but you maybe meant terse. I doubt either should be an objective, so you have a different problem.
Why do you care that this string transformation requires four lines of code? Are you concerned that something that in your mind is one operation ("create transformed string") is spread over four Java operations? You should extract the four lines of Java into their own method. Then, when you read the code where the operation is needed you have one conceptual operation ("create transformed string") corresponding to one Java operation (call a method). You could call the methid createTransformedString to make the code even clearer.
You can use String Builder:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
sb.append("/").append(prodName.charAt(i));
}
sb.append('/').append(prodName);
Or you can put all the code in loop:
int size = 2;
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= size; i++) {
if (i == 0)
sb.append('/');
sb.append(prodName.charAt(i)).append("/");
if (i == size)
sb.append(prodName);
}
I am developing an application in which I came across the requirement where I need to do the replacement of identifying words with the strings i.e. replacing the actual data in templates. In this I am getting the data from an arraylist and for that I have implemented the following solution.
List<String> abc = new ArrayList<String>();
abc.add("willy brown");
abc.add("jamster");
String message="//$^$// has commented on //$^$// .";
String messages[] = message.split(" ");
StringBuffer finalMessage = new StringBuffer();
for(int i=0,j=0; i<messages.length && j<=abc.size(); i++){
System.out.println("messages : " + messages[i]);
if(messages[i].equals("//$^$//")){
messages[i] = abc.get(j);
System.out.println("after changes " +messages[i]);
j++;
}
finalMessage.append(messages[i] +" ");
}
System.out.println("final message: " + finalMessage);
I just want to know if there is any better way to implement this and also if there is any vulnerability in this.
I would use MessageFormat.format for this:
List<String> abc = new ArrayList<String>();
abc.add("willy brown");
abc.add("jamster");
String message = "{0} has commented on {1}";
String finalMessage = MessageFormat.format(message, abc.toArray(new String[abc.size()]));
System.out.println(finalMessage);
You can use the built in String and StringBuffer methods to perform this task without having to break apart the message into an array. I also suggest extracting your field identifier into a separate variable. God forbid you miss-type it somewhere!
String fieldIdentifier = "//$^$//";
List<String> abc = new ArrayList<>();
abc.add("willy brown");
abc.add("jamster");
String message= fieldIdentifier + " has commented on " + fieldIdentifier + ".";
StringBuffer finalMessage = new StringBuffer(message);
int fieldCount = 0;
while(finalMessage.indexOf(fieldIdentifier) > -1) {
int index = finalMessage.indexOf(fieldIdentifier);
finalMessage = finalMessage.replace(index, index + fieldIdentifier.length(), abc.get(fieldCount));
fieldCount++;
}
System.out.println("final message: " + finalMessage);
Edit: using StringBuffer for these kinds of operations is highly preferable, since it is mutable and much faster than using String.
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.