Split String With Some Constraints In Java - java

I have a string like this :
12
I want to get split to [2] ignoring 1. Is it possible to do so in java?

You can use the split() method to split on a regex input or, better yet, if you know the exact position or character you want to split at (as seems to be the case here), just use substring() combined with indexOf(). Something like:
String substring = string.substring(0, indexOf("2"));
where string is your original String variable..

If you know the exact index,
String str = "12"
String s = str.substring(1,2); // output 2
or
String s = str.substring(0, indexOf("2")); //output 2
or
char[] chars = str.toCharArray();
char c = chars[1]; // output

Related

How to remove all String value after getting any space or special character

I want to keep all the characters before a space and remove the rest of the string.
Example:
String str = "Davenport FL 33897 US";
I want to print only "Davenport" and remove the rest of the string. Also the string is dynamic every time.
You need to use substr and indexOf
str.substr(0,str.indexOf(' ')); // "Davenport"
substr(0,X) will give you the sub string of your string starting at index 0 and ending at index X,
Because you want to get the first word until the first space you replace X with:
str.indexOf(' ')
which returns the index of the first space in your string
We can use regular expression to detect space and special character. You can utilize below code to do the same.
String str="Davenport FL 33897 US";
String[] terms = str.split("[\\s#&.?$+-]+");
System.out.println(terms[0]);
It's working for me.
You can use the split function to split the string using ' ' as your delimeter.
const myString = "Davenport FL 33897 US"
const splitString = myString.split(' ')
split() returns an array of strings that separated using the delimeter.
you can just get the index of the first string by.
console.log(splitString[0])
another way would be just to put the index after the split function so that you get only what you want and not the full array.
const firstWord = myString.split(' ')[0]
String[] newOutput = str.split(" ");
String firstPart = newOutput[0];

Add character into middle of String

I need your help to turn a String like 12345678 into 1234.56.78
[FOUR DIGITS].[TWO DIGITS].[TWO DIGITS]
My code:
String s1 = "12345678";
s1 = s1.replaceAll("(\\d{4})(\\d+)", "$1.$2").replaceAll("(\\d{2})(\\d+)", "$1.$2");
System.out.println(s1);
But the result is 12.34.56.78
If you are sure that you'll always have the input in the same format then you can simply use a StringBuilder and do something like this:
String input = "12345678";
String output = new StringBuilder().append(input.substring(0, 4))
.append(".").append(input.substring(4, 6)).append(".")
.append(input.substring(6)).toString();
System.out.println(output);
This code creates a new String by appending the dots to the sub-strings at the specified locations.
Output:
1234.56.78
Use a single replaceAll() method with updated regex otherwise the second replaceAll() call will replace including the first four digits.
System.out.println(s1.replaceAll("(\\d{4})(\\d{2})(\\d+)", "$1.$2.$3")
This puts dots after every pair of chars, except the first pair:
str = str.replaceAll("(^....)|(..)", "$1$2.");
This works for any length string, including odd lengths.
For example
"1234567890123" --> "1234.56.78.90.12.3"

Split string using reges

I have following string
String str = "url:http://www.google.com"
Now I want to split the above string using :.
If I split above string using : then above string split into 3 segments.
But I want whole URL in one segment. How can I get the whole URL?
Three is an one way that I found using substring
String webURL = str.substring(4, str.length());
Is there any other best way to that?
You can call String.split(String, int) where the second argument is a limit (or count). Something like,
String str = "url:http://www.google.com";
String[] arr = str.split(":", 2);
System.out.println(arr[1]);
Output is (as requested)
http://www.google.com
String str= "url:http://www.google.com";
// find the first : and take string beyond that
str = str.substring(str.indexOf(':')+1);
System.out.println(str);

Java- Extract part of a string between two similar special characters

Java- Extract part of a string between two similar special characters.
I want to substring the second number, example :
String str = '1-10-251';
I want the result to be: 10
String str = "1-10-251";
String[] strArray = str.split("-");
System.out.println(strArray[1]);

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";

Categories