How to retrive a specific portion of a String in java - java

I have a requirement that i have to get a specific portion from a String i.e if i have java.lang.String i need to get the com field from the String i have done this
public class uu {
public static void main(String[] args) {
String domain = "www.xyzw.com";
String[] strArray = domain.split("\\.");
for (String str : strArray) {
System.out.println(str);
}
}
}
it is giving me three fields separately but i need the com only ..
someone help me

String s = domain.substring(domain.lastIndexOf(".")+1);
Consider inserting error checks for the case that the string does not contain .

String domain = "www.xyzw.com";
String[] strArray = domain.split("\\.");
System.out.println(strArray[2]);

You can do:
String r = strArray[strArray.length - 1];
Or:
String r = domain.substring(domain.lastIndexOf(".") + 1);

If you work with domains you could use Google Guava InternetDoMainNames class. It is very simple
InternetDomainName.from("www.xyzw.com").publicSuffix();
How to use:
https://code.google.com/p/guava-libraries/wiki/InternetDomainNameExplained
http://koziolekweb.pl/2014/03/30/pomocna-guava-informacje-o-domenie/ (with example - translation to english is posible)

Related

How to add a prefix and suffix to a particular word occurrences in the String?

I am trying to add prefix and suffix to a particular occurrence of the word in the string in java. Can anyone help me and tell me where am i going wrong? Below is my code.
public static void main(String[] args) {
String str = "Hello world. welcome world java.";
String arr[] = str.split("[. ]");
if(str.contains("world")) {
System.out.println("PREFIX_"+str+"_SUFFIX");
}
}
output expected :
Hello PREFIX_world_SUFFIX. welcome PREFIX_world_SUFFIX java
output getting:
PREFIX_Hello world. welcome world java_SUFFIX
String replaced = str.replaceAll("world", "PREFIX_world_SUFFIX");
System.out.println(replaced);
Your code is wrong since you're not changing the str variable while calling the split() function.
Also, from what I can gather, you also want to add prefix and suffix to those words containing "world".
Like if your string is something like this: Hello worldJava! welcome to java world, you'd want to display something like this: Hello PREFIX_worldJava_SUFFIX! welcome to java PREFIX_world_SUFFIX. (Note, the previous answers wouldn't be able to do this kind of substitution).
String str = "Hello world. welcome world java.";
String[] wordArr = str.split("[. ]");
Set<String> words = new HashSet<>(Arrays.asList(wordArr));
for (String w: words) {
if(w.toLowerCase().contains("world")){
str = str.replace(w, "PREFIX_"+ w +"_SUFFIX");
}
}
System.out.println(str);
Note here that I am using java Set to parse unique words from the input string and then replacing them in the original string with the added prefix/suffix.
Just do this simply :
public class Example {
public static void main(String[] args){
String str = "Hello world. welcome world java.";
System.out.println(str.replace("world", "PREFIX_world_SUFFIX"));
}
}
Output :
Hello PREFIX_world_SUFFIX. welcome PREFIX_world_SUFFIX java.
You are doing it wrong on the print side. You can do this.
String stringToCheck = "world";
if(str.contains(stringToCheck)) {
str = str.replaceAll(stringToCheck , "PREFIX_"+stringToCheck+"_SUFFIX");
System.out.println(str);
}

Java - Cut a string programmatically

I have a string (URL) like this:
"https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp"
I need to extract the last part only i.e. 02_Cuppy_lol.webp.
How can I do that?
Thanks!
You can use substring() and lastIndexOf() here:
String value = completeString.substring(completeString.lastIndexOf("/") + 1);
You can split this text/url and get last part, for example:
String url = "https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp";
String[] splittedUrl = url.split("/");
String lastPart = splittedUrl[splittedUrl.length()-1)];
you can use the method split().follow this example
public class Demo {
public static void main(String args[]){
String str ="https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp";
String[] temp=str.split("/");
int lastIndex =temp.length-1;
String lastPart = temp[lastIndex];
System.out.println(lastPart);
}
}
Output-:
02_Cuppy_lol.webp

Any shortest method to get RHS values in the string with comma separated

This is my String
String str = "fus=""192.10.136.111"""," ful=""333333"""," fui=""7b7b7b40000000010000012e55192ab8""", fuc=1, fuq=3, fut=2015-03-30 16:21:36, fud=1, fss=3, fst=2," fsi=""302""", fso=0, fsa=0, fsr=2, cuc=1".
I need only the RHS values without double quotes with comma seperated. For example
192.10.136.111,333333,7b7b7b40000000010000012e55192ab8,1,3,2015-03-30 16:21:36,1,3,2,302,0,0,2,1
The logic should be generic
If you have a string like below (which is basically a CSV of key-value pair)
String str = "fus=\"192.168.1.1\",fus1=\"333333\"";
You can use below code
List<String> values = new ArrayList<>();
String [] keyValuePairs = str.split(",");
for(String keyValuePair : keyValuePairs) {
String [] keyValue = keyValuePair.split("=");
values.add(keyValue[1]);
}
Seeing that this is only your second question, you need to get into a habit of providing MCVE. You posted your problem, but you didn't post an attempt or even an explanation of an attempt.
Having said that, after escaping all of the quotations in your string, you could try simple string manipulations.
public static void main(String[] args) throws Exception {
String str = "fus=\"\"192.10.136.111\"\"\",\" ful=\"\"333333\"\"\",\" fui=\"\"7b7b7b40000000010000012e55192ab8\"\"\", fuc=1, fuq=3, fut=2015-03-30 16:21:36, fud=1, fss=3, fst=2,\" fsi=\"\"302\"\"\", fso=0, fsa=0, fsr=2, cuc=1";
String[] pieces = str.split(",");
for (int i = 0; i < pieces.length; i++) {
pieces[i] = pieces[i].substring(pieces[i].indexOf("=") + 1).replaceAll("\"", "");
}
System.out.println(String.join(",", pieces));
}
Results:

How to remove matched words from end of String

I want to remove the following words from end of String ‘PTE’, ‘LTD’, ‘PRIVATE’ and ‘LIMITED’
i tried the code but then i stuck. i tried this
String[] str = {"PTE", "LTD", "PRIVATE", "LIMITED"};
String company = "Basit LTD";
for(int i=0;i<str.length;i++) {
if (company.endsWith(str[i])) {
int position = company.lastIndexOf(str[i]);
company = company.substring(0, position);
}
}
System.out.println(company.replaceAll("\\s",""));
It worked. But suppose the company is Basit LIMITED PRIVATE LTD PTE or Basit LIMITED PRIVATE PTE LTD or any combination of four words in the end. Then the above code just remove the last name i.e., PTE or PRIVATE and so on, and the output is BasitLIMITEDPRIVATELTD.
I want output to be just Basit
How can i do it?
Thanks
---------------Edit---
Please note here the company name is just an example, it is not necessary that it is always the same. may be i have name like
String company = "Masood LIMITED LTD PTE PRIVATE"
or any name that can have the above mentioned words at the end.
Thanks
You can do this in single line. no need to loop through. just use String#replaceAll(regex, str).
company = company.replaceAll("PTE$*?|LTD$*?|PRIVATE$*?|LIMITED$*?","");
If you place the unwanted words in the map it will be ommitted in the resultant string
HashMap map = new HashMap();
map.put("PTE", "");
map.put("LTD", "");
map.put("PRIVATE", "");
map.put("LIMITED", "");
String company = "Basit LTD PRIVATE PTE";
String words[] = company.split(" ");
String resultantStr = "";
for(int k = 0; k < words.length; k++){
if(map.get(words[k]) == null) {
resultantStr += words[k] + " ";
}
}
resultantStr = resultantStr.trim();
System.out.println(" Trimmed String: "+ resultantStr);
If you want to remove these suffixes only at the end of the string, then you could introduce a while loop:
String[] str = {"PTE", "LTD", "PRIVATE", "LIMITED"};
boolean foundSuffix = true;
String company = "Basit LTD";
while (foundSuffix) {
foundSuffix = false;
for(int i=0;i<str.length;i++) {
if (company.endsWith(str[i])) {
foundSuffix = true;
int position = company.lastIndexOf(str[i]);
company = company.substring(0, position);
}
}
}
System.out.println(company.replaceAll("\\s",""));
If you don't mind transforming PTE Basit LIMITED INC to Basit (and also remove the first PTE), then replaceAll should work, as explained by others.
I was trying to do exactly same thing for one of my projects. I wrote this code few days earlier. Now I was exactly trying to find a much better way to do it, that's how I found this Question. But after seeing other answers I decided to share my version of the code.
Collection<String> stopWordSet = Arrays.asList("PTE", "LTD", "PRIVATE", "LIMITED");
String company = "Basit LTD"; //Or Anything
String[] tokens = company.split("[\#\]\\\_\^\[\"\#\ \!\&\'\`\$\%\*\+\(\)\.\/\,\-\;\~\:\}\|\{\?\>\=\<]+");
Stack<String> tokenStack = new Stack<>();
tokenStack.addAll(Arrays.asList(tokens));
while (!tokenStack.isEmpty()) {
String token = tokenStack.peek();
if (stopWordSet.contains(token))
tokenStack.pop();
else
break;
}
String formattedCompanyName = StringUtils.join(tokenStack.toArray());
Try this :
public static void main(String a[]) {
String[] str = {"PTE", "LTD", "PRIVATE", "LIMITED"};
String company = "Basit LIMITED PRIVATE LTD PTE";
for(int i=0;i<str.length;i++) {
company = company.replaceAll(str[i], "");
}
System.out.println(company.replaceAll("\\s",""));
}
All you need is to use trim() and call your function recursively, Or each time you remove a sub string from the end, reset your i to 0.
public class StringMatchRemove {
public static void main(String[] args) {
String str="my name is noorus khan";
String search="noorus";
String newString="";
String word=str.replace(search," ");
StringTokenizer st = new StringTokenizer(word," ");
while(st.hasMoreTokens())
{
newString = newString + st.nextToken() + " ";
}
System.out.println(newString);
}
first using the replace method we get word=my name is ..... khan (Note: here(.) represents the space). Now we should have to remove these spaces for that we are creating a new string adding all the token simply.
Output: my name is khan

Parsing specific elements of a String in Java

I want to read Object from string expression. eg:
I have following string:
(3:2,1)
or
(3:null,1)
now I want to read Object1=3; Object2=2; Object3=1 or
Object1=3; Object2=null; Object3=1.
How can I read it in Java.
I am usually not a big fan of regular expressions, but this is a perfect example of where the proper application of a regular expression is simpler and most importantly easier to maintain than other String manipulation based solutions.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Parser
{
public static void main(final String[] args)
{
final String s1 = "(3:2,1)";
final String s2 = "(3:null,1)";
final Pattern p = Pattern.compile("\\((\\d+):(\\d+|null),(\\d+)\\)");
final Matcher m1 = p.matcher(s1);
m1.matches();
System.out.format("Object1=%s; Object2=%s; Object3=%s", m1.group(1), m1.group(2), m1.group(3));
System.out.println();
final Matcher m2 = p.matcher(s2);
m2.matches();
System.out.format("Object1=%s; Object2=%s; Object3=%s", m2.group(1), m2.group(2), m2.group(3));
}
}
As per your requirements the expected output looks like
Object1=3; Object2=2; Object3=1
Object1=3; Object2=null; Object3=1
Perhaps, this is what you want:
String s[] = inputString.substring(1, inputString.length() - 2)split(","); // inputString is your string expression
Object object3 = s[1];
String s1[] = s[0].split(":");
Object object1 = s1[0];
Object object2 = s1[1];
If you want null instead of the string "null", you could add a check as this :
Object object2 = s1[1].equals("null") ? null : s1[1];
and similarly convert (parse) to integer if you want:
Object object2 = s1[1].equals("null") ? null : new Integer(s1[1]);
you can parse the string with substring
http://www.roseindia.net/help/java/s/java-substring.shtml
i would think u could do object1 = string
but really you would normally do
object1.variable = string
otherwise its not an "object"
its a "string object"
String str = "3:2,1";
String str2 = "3:null,1";
// first case
Object[] objects = str.split(":|,");
System.out.println(Arrays.asList(objects));
// second case
Object[] objects2 = str2.split(":|,");
System.out.println(Arrays.asList(objects2));

Categories

Resources