How to remove last character in String? [duplicate] - java

This question already has answers here:
Java: Simplest way to get last word in a string
(7 answers)
Closed 2 years ago.
how to remove last word in a string
word should be dynamic
for example:-String [] a={"100-muni-abc"};
i want output like this 100-muni
remove last one-abe

Try:
String a = "100-muni-abc";
String res = a.substring(0, a.lastIndexOf("-"));

Starting from
String str = "100-muni-abc";
Removing the last char
str = str.substring(0,str.length() - 1)
Removing the last 3 chars
str = str.substring(0,str.length() - 3)
A bit late huh?

Try this
String str = "100-muni-abc";
String [] parts = str.split("-");
System.out.println(parts[0]+"-"+parts[1]);

Try this
String text = What is the name of your first love?;
String lastWord = text.substring(text.lastIndexOf(" ")+1);
System.out.println(lastWord);
Output Answer : love?

Related

How to split a String into two arrays based on a delimiter in Java? [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 2 years ago.
I have a String as below
String combinedString = "10.15%34.23%67.8% 89.00%100.00%44.44%";
As you can see above, there is a space between 67.8% and 89.00%
I would want to split them into two String arrays or two strings as below
String[] firstStringArray = {10.15%,34.23%,67.8%};
String[] secondStringArray = {89.00%, 100.00%, 44.44%};
or
String firstString = "10.15%34.23%67.8%";
String secondString = "89.00%100.00%44.44%";
Any idea on this please?
You could simply use String.split(" ") as follows:
String combinedString = "10.15%34.23%67.8% 89.00%100.00%44.44%";
String firstString = combinedString.split(" ")[0];
String secondString = combinedString.split(" ")[1];
System.out.println(firstString);
System.out.println(secondString);
Output would look like this:
10.15%34.23%67.8%
89.00%100.00%44.44%
You can use the white-space regex to split string based on delimiter of space, snippet as below,
String str = "10.15%34.23%67.8% 89.00%100.00%44.44%";
String[] splited = str.split("\\s+");

Java: How to split a String into two separate arrays after a space? [duplicate]

This question already has answers here:
split string only on first instance - java
(6 answers)
Closed 4 years ago.
If a client wants to store a message into a txt file, user uses keyword msgstore followed by a quote.
Example:
msgstore "ABC is as easy as 123"
I'm trying to split msgstore and the quote as two separate elements in an array.
What I currently have is:
String [] splitAdd = userInput.split(" ", 7);
but the problem I face is that it splits again after the second space so that it's:
splitAdd[0] = msgstore
splitAdd[1] = "ABC
splitAdd[2] = is
My question is, how do I combine the second half into a single array with an unknown length of elements so that it's:
splitAdd[0] = msgstore
splitAdd[1] = "ABC is as easy as 123"
I'm new to java, but I know it's easy to do in python with something like (7::).
Any advice?
Why do you have limit parameter as 7 when you want just 2 elements? Try changing it to 2:-
String splitAdd[] = s.split(" ", 2);
OR
String splitAdd[] = new String[]{"msgstore", s.split("^msgstore ")[1]};
substring on the first indexOf "
String str = "msgstore \"ABC is as easy as 123\"";
int ind = str.indexOf(" \"");
System.out.println(str.substring(0, ind));
System.out.println(str.substring(ind));
edit
If these values need to be in an array, then
String[] arr = { str.substring(0, ind), str.substring(ind)};
You can use RegExp: Demo
Pattern pattern = Pattern.compile("(?<quote>[^\"]*)\"(?<message>[^\"]+)\"");
Matcher matcher = pattern.matcher("msgstore \"ABC is as easy as 123\"");
if(matcher.matches()) {
String quote = matcher.group("quote").trim();
String message = matcher.group("message").trim();
String[] arr = {quote, message};
System.out.println(Arrays.toString(arr));
}
This is more readable than substring a string, but it definetely slower. As alternative, you can use substirng a string:
String str = "msgstore \"ABC is as easy as 123\"";
int pos = str.indexOf('\"');
String quote = str.substring(0, pos).trim();
String message = str.substring(pos + 1, str.lastIndexOf('\"')).trim();
String[] arr = { quote, message };
System.out.println(Arrays.toString(arr));

how to extract first substring i a string containg /? [duplicate]

This question already has answers here:
Java: Getting a substring from a string starting after a particular character
(10 answers)
Closed 8 years ago.
I would like to extract ccadmin from /ccadmin/hrp/filelist ?
i know that i can get last substring using
String uri = "/ccadmin/hrp/filelist";
String commandKey = uri.substring(uri.lastIndexOf("/") + 1, uri.length());
but how to extract first Substring ccadmin?
If I understand your question, then you could use something like,
String uri = "/ccadmin/hrp/filelist";
String first = uri.substring(1, uri.indexOf("/", 2));
System.out.println(first);
Output is
ccadmin
Split the string by the / character:
String[] parts = uri.split("/");
parts[1] is what you want.
you can use this to split your string and then get the part of uri you need:
String uri = "/s/d/f";
String[] parts = uri.split("/");
String item = parts[1];
System.out.println( item );

Replace the last occurrence of a string in another string [duplicate]

This question already has answers here:
Replace the last part of a string
(11 answers)
Closed 8 years ago.
Let's say I have a string
string myWord="AAAAA";
I want to replace "AA" with "BB", but only the last occurrence, like so:
"AAABB"
Neither string.replace() nor string.replaceFirst() would do the job.
Is there a string.replaceLast()? And, If not, will there ever be one or is there an alternative also working with regexes?
Find the index of the last occurrence of the substring.
String myWord = "AAAAAasdas";
String toReplace = "AA";
String replacement = "BBB";
int start = myWord.lastIndexOf(toReplace);
Create a StringBuilder (you can just concatenate Strings if you wanted to).
StringBuilder builder = new StringBuilder();
Append the part before the last occurrence.
builder.append(myWord.substring(0, start));
Append the String you want to use as a replacement.
builder.append(replacement);
Append the part after the last occurrence from the original `String.
builder.append(myWord.substring(start + toReplace.length()));
And you're done.
System.out.println(builder);
You can do this:
myWord = myWord.replaceAll("AA$","BB");
$ means at the last.
Just get the last index and do an in place replacement of the expression with what you want to replace.
myWord is the original word sayAABDCAADEF. sourceWord is what you want to replace, say AA
targetWord is what you want to replace it with say BB.
StringBuilder strb=new StringBuilder(myWord);
int index=strb.lastIndexOf(sourceWord);
strb.replace(index,sourceWord.length()+index,targetWord);
return strb.toString();
This is useful when you want to just replace strings with Strings.A better way to do it is to use Pattern matcher and find the last matching index. Take as substring from that index, use the replace function there and then add it back to the original String. This will help you to replace regular expressions as well
String string = "AAAAA";
String reverse = new StringBuffer(string).reverse().toString();
reverse = reverse.replaceFirst(...) // you need to reverse needle and replacement string aswell!
string = new StringBuffer(reverse).reverse().toString();
It seems like there could be a regex answer to this.
I initially was trying to solve this through regex, but could not solve for situations like 'AAAzzA'.
So I came up with this answer below, which can handle both 'AAAAA' and 'AAAzzA'. This may not be the best answer, but I guess it works.
The basic idea is to find the last index of 'AA' occurrence and split string by that index:
String myWord = "AAAAAzzA";
String source = "AA";
String target = "BB";
int lastIndex = -1;
if ((lastIndex = myWord.lastIndexOf(source)) >= 0) {
String f = myWord.substring(0, lastIndex);
String b = myWord.substring(lastIndex + target.length() >= myWord
.length() ? myWord.length() : lastIndex + target.length(),
myWord.length());
myWord = f + target + b;
}
System.out.println(myWord);
myWord=myWord.replaceAll("AA(?!A)","BB");
You can do this with String#subtring
myWord= myWord.substring(0, myWord.length() - 2) + "BB";

how to count special character in a string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String Functions how to count delimiter in string line
I have a string as str = "one$two$three$four!five#six$" now how to count Total number of "$" in that string using java code.
Using replaceAll:
String str = "one$two$three$four!five#six$";
int count = str.length() - str.replaceAll("\\$","").length();
System.out.println("Done:"+ count);
Prints:
Done:4
Using replace instead of replaceAll would be less resource intensive. I just showed it to you with replaceAll because it can search for regex patterns, and that's what I use it for the most.
Note: using replaceAll I need to escape $, but with replace there is no such need:
str.replace("$");
str.replaceAll("\\$");
You can just iterate over the Characters in the string:
String str = "one$two$three$four!five#six$";
int counter = 0;
for (Character c: str.toCharArray()) {
if (c.equals('$')) {
counter++;
}
}
String s1 = "one$two$three$four!five#six$";
String s2 = s1.replace("$", "");
int result = s1.length() - s2.length();

Categories