Get value from 2nd slash - java

Below is my string
/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk
I want to get the value after 2nd slash(/) which is
D:/coinFiles/Coin-v1.1.8.apk
How should I do this?
Note :
I am getting this string in my rest call in variable restOfTheUrl
#RequestMapping(value="/downloadAPK/**", method = RequestMethod.GET)
public void downloadFile(HttpServletResponse response, HttpServletRequest request) throws IOException {
String restOfTheUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
}
I want to get the complete file location

Even a better and simple solution \\/.*?\\/(.*)
Regex Demo
\\/.*?\\/(.*) : \\/.*?\\/ match the first two / and content between
(.*) : capture whatever is after first two /
String s = "/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk";
String result=s.replaceAll("\\/.*?\\/(.*)", "$1");
System.out.println(result);
Output :
D:/coinFiles/Coin-v1.1.8.apk
You can use a regex with replceAll if there is always one : in the input
String s = "/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk";
String result=s.replaceAll(".*([A-Za-z]:.*)", "$1");
System.out.println(result);
Output :
D:/coinFiles/Coin-v1.1.8.apk
.*([A-Za-z]:.*) : .* matches any character
([A-Za-z]:.*) : [A-Za-z] match a character like D
() : is a capturing group which is represented as $1
:.* : will capture all after :
Otherwise
String s = "/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk";
// find first index of /
int index =s.indexOf("/");
// find second index of /
index=s.indexOf("/", index+1);
// fetch substring from second index+1 of /
System.out.println(s.substring(index+1));
Output :
D:/coinFiles/Coin-v1.1.8.apk

If you are sure, always colon(:) will exist in string, then you can use this.
import java.io.*;
public class Test {
public static void main(String args[]) {
String str = new String("/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk");
String subStr1 = new String(":");
System.out.println("value "+ str.substring(str.indexOf( subStr1 )-1));
}
}
output:
value D:/coinFiles/Coin-v1.1.8.apk
This code for without colon (:)
public class HelloWorld{
public static void main(String args[]) {
String str = new String("/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk");
System.out.println("before value" + str);
str = getPattern(str, 2);
System.out.println("\nAfter value "+ str);
}
public static String getPattern(String str, Integer pos) {
for(int i = 0; i< pos; i ++) {
str = str.substring(str.indexOf("/") +1);
}
return str;
}
}
Output
before value/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk
After value D:/coinFiles/Coin-v1.1.8.apk

You can iteratively find the index. You could also write a recursive version, but this does not perform the substring until the final step; which means it will not pollute the String pool.
public class StringUtil {
public static void main(String[] args) {
String path = "/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk";
System.out.println(substring2(path, "/", 2)); // D:/coinFiles/Coin-v1.1.8.apk
String test = "this---is---a---test";
System.out.println(substring2(test, "---", 3)); // test
}
public static String substring2(String src, String str, int offset) {
if (offset <= 0) {
return src;
}
int index = -1, pos = 0;
while (pos++ < offset) {
index = src.indexOf(str, index + 1);
}
return src.substring(index + str.length(), src.length());
}
}
Here is a StringTokenizer version which handles indexing for you.
import java.util.Enumeration;
import java.util.StringTokenizer;
public class StringUtil {
public static void main(String[] args) {
String path = "/downloadAPK/D:/coinFiles/Coin-v1.1.8.apk";
System.out.println(substring2(path, "/", 1)); // D:/coinFiles/Coin-v1.1.8.apk
String test = "this---is---a---test";
System.out.println(substring2(test, "---", 3)); // test
}
public static String substring2(String src, String delim, int offset) {
StringTokenizer tokenizer = new StringTokenizer(src, delim);
while (offset-- > 0 && tokenizer.hasMoreTokens()) {
tokenizer.nextToken();
}
return join(tokenizer, delim);
}
public static <T> String join(Enumeration<T> enumeration, String delim) {
StringBuffer buff = new StringBuffer();
while (enumeration.hasMoreElements()) {
buff.append(enumeration.nextElement());
if (enumeration.hasMoreElements()) {
buff.append(delim);
}
}
return buff.toString();
}
}

Related

When I want to abbreviate two words I get error

I want to abbreviate names that given names include 3 names or more.
Also, I want to put '.' between them.
Thank you
For example
sam harris dorothy
my expectation output like below
s.h.d
My code like this
public class AbbreviateTwoWords {
public static void main(String[] args) {
String shs = abbrevName("Sam Harris");
System.out.println(shs);
}
public static String abbrevName(String name) {
String[] splitnamelist = name.split(" ");
char[] shortform = new char[10];
String point = ".";
int initial = 0;
for (String i : splitnamelist) {
if (initial % 2 == 0) {
shortform[initial] = i.charAt(0);
initial++;
} else {
shortform[initial]=point;
initial++;
}
return new String(shortform);
}
}
}
why complicate and use char array, im guessing its something with the indexes at any rate just use string and concatenate:
public static String abbrevName(String name) {
String[]splitnamelist=name.split(" ");
String shortform="";
for (String currentName:splitnamelist) {
shortform=shortform+currentName.charAt(0);
shortform=shortform+".";
}
//remove the last dot
if (shortform.length()>0)
{
shortform=shortform.substring(0, shortform.length()-1);
}
return shortform;
}
public class AbbreviateName {
public static void main(String[] args) {
AbbreviateName shs = new AbbreviateName();
shs.abbrevName("sam harris dorothy");
}
public void abbrevName(String name) {
String splitName[] = name.split(" "), seperatedName="";
int i=0; // To remove the last "+" sign.
for(String key : splitName){
seperatedName+=key;
if(i<splitName.length-1) {
seperatedName += "+";
}
i++;
}
int k;
System.out.print(seperatedName.charAt(0)+".");
//First letter always displayed
for(int j = 0,l=0; j<seperatedName.length()-1; j++){
k=j;
if(seperatedName.charAt(j)=='+'){
System.out.print(seperatedName.charAt(++k)+".");
// Letter succeeding "+" will be printed.
}
}
}
}
If you are allowed to use Java 8+ streams, you could create abbreviations like this:
import java.util.*;
import java.util.stream.*;
public class Main {
public static String abbreviate(String input) {
if (null == input || input.isEmpty()) {
// nothing to abbreviate
return input;
}
return Arrays.stream(input.split("[.\\s]+")) // split input line by 1 or more whitespaces or dot
.map(s -> s.substring(0, 1)) // get first letter
.collect(Collectors.joining(".")); // join letters into string with "." delimiter
}
}
In this code a dot "." is also included into delimiters to properly handle an abbreviation existing in the input string.
Test and online demo:
public static void main(String[] args) {
String[] inputs = {
"Jerome K. Jerome",
"Robert Louis Stevenson",
"Charles Lutwidge Dodgeson"
};
for (String s : inputs) {
System.out.printf("'%s' -> '%s'%n", s, abbreviate(s));
}
}
Output:
'Jerome K. Jerome' -> 'J.K.J'
'Robert Louis Stevenson' -> 'R.L.S'
'Charles Lutwidge Dodgeson' -> 'C.L.D'
In Java8, we can do this in a few lines.
String shs = "sam harris dorothy";
String shortform = Arrays.stream(shs.split(" "))
.map(s -> s.substring(0, 1))
.map(s -> s.concat("."))
.collect(Collectors.joining());
This is the output:
System.out.println(shortform); //Output is: s.h.d.
System.out.println(shortform.substring(0, shortform.length()-1)); //Output is: s.h.d

What is equivalent to .replaceSecond or .replaceThird?

In this code, we remove the substring "luna" from email string using the .replaceFirst method. We are removing the characters in between + and #. But this happens only in the first instance because we used .replaceFirst. What if we wanted to target the second instance of + and # to remove "smith"?
Our output now is alice+#john+smith#steve+oliver# but we want alice+luna#john+#steve+oliver#
public class Main {
public static void main(String[] args) {
String email = "alice+luna#john+smith#steve+oliver#";
String newEmail = email.replaceFirst("\\+.*?#", "");
System.out.println(newEmail);
}
}
You can find the second + like so:
int firstPlus = email.indexOf('+');
int secondPlus = email.indexOf('+', firstPlus + 1);
(You need to handle the case that there aren't two +s to find, if necessary).
Then find the following #:
int at = email.indexOf('#', secondPlus);
Then stitch it back together:
String newEmail = email.substring(0, secondPlus + 1) + email.substring(at);
or
String newEmail2 = new StringBuilder(email).delete(secondPlus + 1, at).toString();
Ideone demo
Unfortunately Java doesn't have methods like replace second, replace third etc. You can either replaceAll (which will replace all occurences) OR invoce replaceFirst again on the already replaced string. That's basically replacing the second. If you want to replace ONLY the second - then you can do it with substrings or do a regex matcher and iterate on results.
public static void main(String[] args) {
String email = "alice+luna#john+smith#steve+oliver#";
String newEmail = email.replaceFirst("\\+.*?#", "");
newEmail = newEmail .replaceFirst("\\+.*?#", ""); //this replaces the second right? :)
newEmail = newEmail .replaceFirst("\\+.*?#", ""); // replace 3rd etc.
System.out.println(newEmail);
}
You can alternate value of parameter n in following replaceNth method to 2, 3 to perform exactly the same operation as that of replaceSecond or replaceThird. ( Note: this method can be applied in any other value of n. If nth pattern do not exist , it simply return given string ).
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static String replaceNth(String str, int n, String regex, String replaceWith) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
n--;
if (n == 0) {
return str.substring(0,m.start() + 1)+ replaceWith + str.substring(m.end() - 1);
}
}
return str;
}
public static void main(String args[]) {
String email = "alice+luna#john+smith#steve+oliver#";
System.out.println(replaceNth(email, 2, "\\+.*?#", ""));
}
}
I think it is better to encapsulate this logic into separate method, where String and group position are arguments.
private static final Pattern PATTERN = Pattern.compile("([^+#]+)#");
private static String removeSubstringGroup(String str, int pos) {
Matcher matcher = PATTERN.matcher(str);
while (matcher.find()) {
if (pos-- == 0)
return str.substring(0, matcher.start()) + str.substring(matcher.end() - 1);
}
return str;
}
Additionally, you can add more methods, to simplify using this util; like removeFirst() or removeLast()
public static String removeFirst(String str) {
return removeSubstringGroup(str, 0);
}
public static String removeSecond(String str) {
return removeSubstringGroup(str, 1);
}
Demo:
String email = "alice+luna#john+smith#steve+oliver#";
System.out.println(email);
System.out.println(removeFirst(email));
System.out.println(removeSecond(email));
System.out.println(removeSubstringGroup(email, 2));
System.out.println(removeSubstringGroup(email, 3));
Output:
alice+luna#john+smith#steve+oliver#
alice+#john+smith#steve+oliver#
alice+luna#john+#steve+oliver#
alice+luna#john+smith#steve+#
alice+luna#john+smith#steve+oliver#
Ideone demo

remove extra letters and numbers from parenthesis in a string

I have a string like:
(aeiou 123) word one
How can I remove everything from the parenthesis so that only "word one" remains?
You could use a regex, e.g.:
String str = "(aeiou 123) word one";
str = str.replaceAll("\\([^\\)]*\\)", "").trim();
public class ParanthesisRemoval {
public static void main(String args[])
{
String test="ab(xy)cd(zw)ef";
boolean modified = true;
while(modified)
{
modified = false;
int indexOpenParanthesis = test.indexOf("(");
int indexClosedParanthesis = test.indexOf(")");
if(indexOpenParanthesis!=-1 && indexClosedParanthesis!=-1 && indexOpenParanthesis<indexClosedParanthesis)
{
int stringLength = test.length();
test = test.substring(0, indexOpenParanthesis)+test.substring(indexClosedParanthesis+1, stringLength);
modified=true;
}
}
System.out.println(test);
}
}
note that this will not work for nested parantesis - (()), or paranthesis not properly paired (()

I am trying to parse this string and get the last word

Is there something I am doing wrong here? When printed I get "*" and I need to get "-32". I am parsing each individual word and returning the last word.
public static void main(String[] args) {
System.out.println(stringParse("3 - 5 * 2 / -32"));
}
public static String stringParse(String string) {
String[] word = new String[countWords(string)];
string = string + " ";
for (int i = 0; i <= countWords(string); i++) {
int space = string.indexOf(" ");
word[i] = string.substring(0, space);
string = string.substring(space+1);
}
return word[countWords(string)];
}
public static int countWords(String string) {
int wordCount = 0;
if (string.length() != 0) {
wordCount = 1;
}
for (int i = 0; i <= string.length()-1; i++){
if (string.substring(i,i+1).equals(" ")) {
wordCount++;
}
}
return wordCount;
}
You could instead split the string by white space using "\\s+" and return the last element of that array. This will return the last word.
public static String stringParse(String s){
return s.split("\\s+")[s.split("\\s+").length-1];
}
In this case you can use regular expressions too :
public static void main(String[] args) {
System.out.println(stringParse("3 - 5 * 2 / -32"));
}
public static String stringParse(String string) {
String found = null;
Matcher m = Pattern.compile("\\s((\\W?)\\w+)$", Pattern.CASE_INSENSITIVE)
.matcher(string);
while (m.find()) {found = m.group();}
return found;
}

How can return part of a string between two comma characters?

say I'm given a set of strings that looks like this:
0,test0,dummy
1,test,dummy
2,test1,dummy
3,test2,dummy
4,test3,dum,dum,dummy
I wrote code that can return only what's before the last ",":
public class RandomTest {
public static void main(String[] args) {
String testFile = "synsets11.txt";
In testIn = new In(testFile);
while (testIn.hasNextLine()) {
String line = testIn.readLine();
String result = line.substring(0, line.lastIndexOf(","));
List<String> synList = Arrays.asList(result.split(","));
for (String i : synList) {
System.out.println(i);
}
}
}
}
What I intended to do was only return the part of the string that was between the first and second "," characters, so my code above doesn't work for the last line of text. How do I only return what's between the first and second comma?
In this case, only test0, test, test1, test2, and test3.
thanks!
use split() method like this :
public static void main(String[] args) {
String s = "0,prop,dummy";
System.out.println(s.split(",")[1]);
}
O/P:
prop
NOTE : You have to check whether the String contains atleast 1 , (unless you want an ArrayIndexOutOfBoundsException :P)
Rather than using lastIndexOf, use indexOf twice:
int pos = line.indexOf(',', line.indexOf(',')+1);
String result = line.substring(0, pos);
You could use string.replaceAll function.
string.replaceAll("(?m)^[^,]*,|,.*", "");
DEMO
String s = "0,test0,dummy\n" +
"1,test,dummy\n" +
"2,test1,dummy\n" +
"3,test2,dummy\n" +
"4,test3,dum,dum,dummy";
System.out.println(s.replaceAll("(?m)^[^,]*,|,.*", ""));
What about StringTokenizer?
public class RandomTest {
public static void main(String[] args) {
String testFile = "synsets11.txt";
In testIn = new In(testFile);
StringTokenizer stok = null;
while (testIn.hasNextLine()) {
String line = testIn.readLine();
stok = new StringTokenizer(line,",");
for(int i = 0; i< stok.countTokens() ; i++){
String str = st.nextToken();
if( i == 1){
System.out.println(str);
}else if( i > 1){break;}
}// for
}// while
}//main
}//class

Categories