Java Strings with Delimiters - java

I have a string "content/users/user/missions/mission" .I need to get "content/users/user/missions" from it [i.e. string upto the last delimiter] .How to proceed ?

If your requirement is that simple then you could do the following:
String string = "content/users/user/missions/mission";
String newString = string.substring(0, string.lastIndexOf('/'));
There are more fancy ways of doing this, regex could be one.

Use lastIndexOf and substring methods from String class.
String str = "content/users/user/missions/mission";
String result = str.substring(0,str.lastIndexOf('/'));

Related

How to fix ReplaceAll function in java code

i am trying to replace all occurrences of the first character in a string with another using the replace all function. However, no change occurs when i run the function. I tried to target the first character of the original string and then carry the out the replacement but no luck. Below is a snippet of my code.
public static String charChangeAt(String str, String str2) {
//str = x.xy
//str2 = d.w
String res = str.replaceAll(Character.toString(str.charAt(0)), str2);
return res ;
}
Your code replaces all characters that match the first character. If your string is abcda and you run your function, it will replace all occurences of a with whatever you put. Including the last one.
To achieve your goal you should probably not use replaceAll.
You could use StringBuilder.
StringBuilder builder = new StringBuilder(str);
myName.setCharAt(0, str2.charAt(0));
In case you want to replace all occurrences of the first character in a string with another, you can use replace instead of replaceAll. Below is the code snippet.
String str = "x.xy";
String str2 = "d.w";
String res = str.replace(Character.toString(str.charAt(0)), str2);
return res; // will output d.w.d.wy
Your function works fine but you probably are using it the wrong way.
For these strings:
String str = "abaca";
String str2 = "x";
if you do:
charChangeAt(str, str2);
this will not affect str.
You must assign the value returned by your function to str:
str = charChangeAt(str, str2);
This will change the value of str to:
"xbxcx"

What is the efficient way to get a specific substring from a string in Java?

I have a string as follows:
"[error=<null>,EntityID=105378032, Context=<null>]"
and i want to extract the EntityID( in this case 105378032), but i want a generalize solution of doing it.
What is the most efficient way of doing it.
I don't want to traverse the string and get that part.
Did you try regex like .*EntityID=(.*?),.* which mean get the group of characters between EntityID= and the next comma , using replaceAll :
String str = "[error=,EntityID=105378032, Context=]";
System.out.println(str.replaceAll(".*EntityID=(.*?),.*", "$1"));// output 105378032
regex demo
Using Regular expressions seems to be the best way out.
This code works:
String str = "[error=,EntityID=105378032, Context=]";
String[] arr = str.split("EntityID="); //splits it on the part "EntityID="
String[] arr1 = arr[1].split(","); // splits it on the next comma in the 'right' half of your string.
System.out.println(arr1[0]); //prints the 'left' half before the comma.
Ideone link here.
Hope this helps!
You can use this method it's work like a charm
public static String getSubString(String mainString, String lastString, String startString) {
String endString = "";
int endIndex = mainString.indexOf(lastString);
int startIndex = mainString.indexOf(startString);
endString = mainString.substring(startIndex, endIndex);
return endString;
}
Result:
String resultStr = getSubString(yourFullString,",Context","EntityID=");
Happy codding.

Java check and parse out string containing character sequence

I need to dynamically check for presence of char sequence "(Self)" in a string and parse it out.
So if my string say myString is
"ABCDEF (Self)"
it should return myString as
"ABCDEF"
What is the best way of doing it? Can it be done in a single step?
You may use the replace function as follows:
myString = myString.replace(" (Self)","");
Here, read more about things to note with String.replace or the function definition itself. Note that it is overloaded with a char variant, so you can do two kinds of things with a similar function call.
You may use the replaceAll method from the String class as follows:
myString = myString.replaceAll(Pattern.quote("(Self)"), ""));
Try following:
String test="ABCDEF (Self)";
test=test.replaceAll("\\(Self\\)", "");
System.out.println(test.trim());
Output :
ABCDEF
The dig is to use Regular Expressions for more on it visit this link.
And the code won't have a problem if there is no Self in string.
Just check out the String class' public methods.
String modifyString(String str) {
if(str.contains("(Self)")) {
str = str.replace("(Self)", "");
str = str.trim();
}
return str;
}
From the question, I understand that from source string ABCDEF (Self) also the space between F and ( should be removed.
I would recommend to use regEx if you are comfortable with it, else:
String OrigString = "ABCDEF (Self)";
String newString= OrigString.replaceAll("\\(Self\\)", "").trim();
System.out.println("New String : --" +newString+"--");
The Regular Expression for your case would be:
\s*\(Self\)\s*
Tested Java Code using regular expression would be:
String newRegExpString = OrigString.replaceAll("\\s*\\(Self\\)\\s*", "");
System.out.println("New String : -" +newRegExpString+"--");
Output:
New String : --ABCDEF--
New String : -ABCDEF--

Split a String In Java against the split rule?

I have a string like this:
String str="\"myValue\".\"Folder\".\"FolderCentury\"";
Is it possible to split the above string by . but instead of getting three resulting strings only two like:
columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";
Or do I have to use an other java method to get it done?
Try this.
String s = "myValue.Folder.FolderCentury";
String[] a = s.split(java.util.regex.Pattern.quote("."));
Hi programmer/Yannish,
First of all the split(".") will not work and this will not return any result. I think java String split method not work for . delimiter, so please try java.util.regex.Pattern.quote(".") instead of split(".")
As I posted on the original Post (here), the next code:
String input = "myValue.Folder.FolderCentury";
String regex = "(?!(.+\\.))\\.";
String[] result=input.split(regex);
System.out.println("result: "+Arrays.toString(result));
Produces the required output (an array with two values):
result: [myValue.Folder, FolderCentury]
If the problem you're trying to solve is really that specific, you could do it even without using regular expression matches at all:
int lastDot = str.lastIndexOf(".");
columnArray[0] = str.substring(0, lastDot);
columnArray[1] = str.substring(lastDot + 1);

String manipulation in java to get another string

I have the String content://com.android.contact/data/5032 in a variable Str1. I want to manipulate Str1 so that I will get 5032 in another string variable.
Can anyone suggest the answer?
String str1 = "content://com.android.contact/data/5032"
String val = str1.substring(str1.lastIndexOf("//")+1);
If you want go get digits from the given string try this:
String str = "content://com.android.contact/data/5032";
String str2 = str.replaceAll("\\D+","");
System.out.println(str2);
Output:
5032
If you want to split try this:
String[] string = str.split("//|/");
System.out.println(string[string.length -1 ]);
Output:
5032
String str1 = "content://com.android.contact/data/5032";
String str2 = str1.substring(str1.lastIndexOf("/")+1, str1.length());
if you only want the last 4 chars, you can do something like this
String s = "this is a string";
String ss = s.substring(s.length()-4, s.length());
but if you need to extract the number from random positions, you will have to use regular expressions.
Please write names of variables starting with a small letter. You can use the split method to do this. You might find this related question interesting: How to split a string in Java.

Categories

Resources