Get URL part only android - java

I have the URL
http://www.facebook.com/post/ll.html
I want to spilt the url into http://www.facebook.com/post/ and ll.html
Please help

One way of doing this is:
String myStr = "http://www.facebook.com/post/ll.html";
String strEnd = myStr.substring(myStr.lastIndexOf('/')+1);
strEnd will have the string you desire.

String x = "http://www.facebook.com/post/ll.html";
String[] splits = x.split("/");
String last = splits[splits.length - 1];
String first = x.substring(0, x.length() - last.length());
System.out.println(last); // 11.html
System.out.println(first); // http://www.facebook.com/post/

I think the best way to approach this is to also use the URL class, as there are a lot of gotchas if you just do simple string parsing. For your example:
// Get ll.html
String filePart = url.getPath().substring(url.getPath().lastIndexOf('/')+1);
// Get /post/
String pathPart = url.getPath().substring(0, url.getPath().lastIndexOf('/')+1);
// Cut off full URL at end of first /post/
pathPart = url.toString().substring(0, url.toString().indexOf(pathPart)+pathPart.length());
This will even cope with URLs like http://www.facebook.com:80/ll.html/ll.html#foo/bar?wibble=1/ll.html.

Try this:
if (null != str && str.length() > 0 )
{
int endIndex = str.lastIndexOf("/");
if (endIndex != -1)
{
String firststringurl = str.substring(0, endIndex);
String secondstringurl = str.substring(endIndex);
}
}

Related

How to replace a particular string with value in java

EDIT :
Goal : http://localhost:8080/api/upload/form/test/test
Is it possible to have some thing like `{a-b, A-B..0-9}` kind of pattern and match them and replace with value.
i have following string
http://localhost:8080/api/upload/form/{uploadType}/{uploadName}
there can be any no of strings like {uploadType}/{uploadName}.
how to replace them with some values in java?
[Edited] Apparently you don't know what substitutions you'll be looking for, or don't have a reasonable finite Map of them. In this case:
Pattern SUBST_Patt = Pattern.compile("\\{(\\w+)\\}");
StringBuilder sb = new StringBuilder( template);
Matcher m = SUBST_Patt.matcher( sb);
int index = 0;
while (m.find( index)) {
String subst = m.group( 1);
index = m.start();
//
String replacement = "replacement"; // .. lookup Subst -> Replacement here
sb.replace( index, m.end(), replacement);
index = index + replacement.length();
}
Look, I'm really expecting a +1 now.
[Simpler approach] String.replace() is a 'simple replace' & easy to use for your purposes; if you want regexes you can use String.replaceAll().
For multiple dynamic replacements:
public String substituteStr (String template, Map<String,String> substs) {
String result = template;
for (Map.Entry<String,String> subst : substs.entrySet()) {
String pattern = "{"+subst.getKey()+"}";
result = result.replace( pattern, subst.getValue());
}
return result;
}
That's the quick & easy approach, to start with.
You can use the replace method in the following way:
String s = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}";
String typevalue = "typeValue";
String nameValue = "nameValue";
s = s.replace("{uploadType}",value).replace("{uploadName}",nameValue);
You can take the string that start from {uploadType} till the end.
Then you can split that string using "split" into string array.
Were the first cell(0) is the type and 1 is the name.
Solution 1 :
String uploadName = "xyz";
String url = "http://localhost:8080/api/upload/form/" + uploadName;
Solution 2:
String uploadName = "xyz";
String url = "http://localhost:8080/api/upload/form/{uploadName}";
url.replace("{uploadName}",uploadName );
Solution 3:
String uploadName = "xyz";
String url = String.format("http://localhost:8080/api/upload/form/ %s ", uploadName);
String s = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}";
String result = s.replace("uploadType", "UploadedType").replace("uploadName","UploadedName");
EDIT: Try this:
String r = s.substring(0 , s.indexOf("{")) + "replacement";
The UriBuilder does exactly what you need:
UriBuilder.fromPath("http://localhost:8080/api/upload/form/{uploadType}/{uploadName}").build("foo", "bar");
Results in:
http://localhost:8080/api/upload/form/foo/bar

Java: slicing a String

I have URLs which always end on a number, for example:
String url = "localhost:8080/myproject/reader/add/1/";
String anotherurl = "localhost:8080/myproject/actor/take/154/";
I want to extract the number between the last two slashes ("/").
Does anyone know how I can do this?
You could split the string:
String[] items = url.split("/");
String number = items[items.length-1]; //last item before the last slash
With a regular expression:
final Matcher m = Pattern.compile("/([^/]+)/$").matcher(url);
if (m.find()) System.out.println(m.group(1));
Use lastIndexOf, like this:
String url = "localhost:8080/myproject/actor/take/154/";
int start = url.lastIndexOf('/', url.length()-2);
if (start != -1) {
String s = url.substring(start+1, url.length()-1);
int n = Integer.parseInt(s);
System.out.println(n);
}
That's the basic idea. You'll have to do some error checking (for example, if a number is not found at the end of the URL), but it will work fine.
For the inputs which you specified
String url = "localhost:8080/myproject/reader/add/1/";
String anotherurl = "localhost:8080/myproject/actor/take/154/";
adding a little error handling to handle missing "/" like
String url = "localhost:8080/myproject/reader/add/1";
String anotherurl = "localhost:8080/myproject/actor/take/154";
String number = "";
if(url.endsWith("/") {
String[] urlComps = url.split("/");
number = urlComps[urlComps.length-1]; //last item before the last slash
} else {
number = url.substring(url.lastIndexOf("/")+1, url.length());
}
In One Line :
String num = (num=url.substring(0, url.length() - 1)).substring(num.lastIndexOf('/')+1,num.length());

Remove string after last occurrence of a character

In my application, I am appending a string to create path to generate a URL. Now I want to remove that appended string on pressing back button.
Suppose this is the string:
/String1/String2/String3/String4/String5
Now I want a string like this:
/String1/String2/String3/String4/
How can I do this?
You can use lastIndexOf() method for same with
if (null != str && str.length() > 0 )
{
int endIndex = str.lastIndexOf("/");
if (endIndex != -1)
{
String newstr = str.substring(0, endIndex); // not forgot to put check if(endIndex != -1)
}
}
String whatyouaresearching = myString.substring(0, myString.lastIndexOf("/"))
You can use org.apache.commons.lang3.StringUtils.substringBeforeLast which is null-safe.
From the javadoc:
// The symbol * is used to indicate any input including null.
StringUtils.substringBeforeLast(null, *) = null
StringUtils.substringBeforeLast("", *) = ""
StringUtils.substringBeforeLast("abcba", "b") = "abc"
StringUtils.substringBeforeLast("abc", "c") = "ab"
StringUtils.substringBeforeLast("a", "a") = ""
StringUtils.substringBeforeLast("a", "z") = "a"
StringUtils.substringBeforeLast("a", null) = "a"
StringUtils.substringBeforeLast("a", "") = "a"
Maven dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8</version>
</dependency>
Easiest way is ...
String path = "http://zareahmer.com/questions/anystring";
int pos = path.lastIndexOf("/");
String x =path.substring(pos+1 , path.length()-1);
now x has the value stringAfterlastOccurence
The third line in Nepster's answer should be
String x =path.substring(pos+1 , path.length());
and not String x =path.substring(pos+1 , path.length()-1); since substring() method takes the end+1 offset as the second parameter.

Using regex on XML, avoid greedy match

It looks simple problem , but I'll apprisiate any help here :
I need to swap password value (can be any value) to "****"
The origunal sting is string resived from xml
The problem is that I getting as output only line:
<parameter><value>*****</value></parameter>
But I need the whole string as output only with password value replaced
Thank you in advance
String originalString = "<parameter>" +
"<name>password</name>"+
"<value>my123pass</value>"+
"</parameter>"+
"<parameter>"+
"<name>LoginAttempt</name>"+
"<value>1</value>"+
"</parameter>";
System.out.println("originalString: "+originalString);
Pattern pat = Pattern.compile("<name>password</name><value>.*</value>");
Matcher mat = pat.matcher(originalString);
System.out.println("NewString: ");
System.out.print(mat.replaceFirst("<value>***</value>"));
mat.reset();
If I'm not mistaken, you want to change the password in the string with *'s. You can do it by using String methods directly. Just get the last index of the starting value tag and iterate until you reach a "<", replacing the value between those two with *'s. Something like this:
int from = originalString.lastIndexOf("<name>password</name><value>");
bool endIteration = false;
for(i = from + 1 ; i < originalString.length() && !endIteration ; i ++) {
if(originalString.toCharArray()[i] == '<')
endIteration = true;
else {
originalString.toCharArray()[i] = '*';
}
}
EDIT: There is another way making a proper use of all the String class goodies:
int from = originalString.lastIndexOf("<name>password</name><value>");
int to = originalString.indexOf("</value>", from);
Arrays.fill(originalString.toCharArray(), from, to, '*');

Extract string text into another strings

I got a string like this:
String text = number|name|url||number2|name2|url2
Now I have written a loop
int initialiaze = 0;
for(i = initialize; i > text.length(); i++) {
//do the work
}
In this loop I want to extract number to one string, name to one string, url to one string and if I reach || do a action (e.g insert this three string into db) if this action is done, start again an extract number2, name2 and url2 into string and do a action.
Is this possible? Can you tell me how? I dont get it.
you can use .split() method for strings.
String[] bigParts = myString.split("\\|\\|");
for(String part : bigParts)
{
String[] words = part.split("\\|");
//save to db or what you want
}
for your case
StringTokenizer stPipe = null;
StringTokenizer stDblPipe = null;
String firstPipeElement=null;
stPipe = new StringTokenizer(text, "|");
if (stPipe.hasMoreElements())
{
firstPipeElement= stPipe.nextElement().toString();
.......
if(firstPipeElement.equals("||"))
{
stDblPipe = new StringTokenizer(firstPipeElement , "||");
.....
}
}
hope this helps
Java is not my language, but worth try,
String text = number|name|url||number2|name2|url2
String[] temp;
String[] temp2;
int i ;
temp = text.split("\\|\\|")
for(i=0;i<temp.length();i++){
temp2 = temp[i].split("\\|");
String no = temp2[0];
String name = temp2[1];
String url = temp2[2];
// Do processing with no, name, url
}
I hope, this would help

Categories

Resources