Add character into middle of String - java

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"

Related

Java - Remove only the first backslash

Small Java question regarding how to remove only the first backslash please.
I have a string which looks like this:
String s = "\\u6df1\\u5733";
Please note, there are two backslashes, and multiple occurrences.
Hence, when this is displayed, the visual result is:
\深\圳
I would like to just remove any extra backslashes, having a result like this:
深圳
So far, I have tried this:
String s = "\\u6df1\\u5733";
String ss = s.replaceAll("\\", "");
But it is still not working.
What is the correct solution please in order to get 深圳 from "\\u6df1\\u5733" please?
Thank you
Try this.
String s = "\\u6df1\\u5733";
Pattern UNICODE_ESCAPE = Pattern.compile("\\\\u[0-9a-f]+", Pattern.CASE_INSENSITIVE);
String ss = UNICODE_ESCAPE.matcher(s).results()
.map(x -> new String(Character.toChars(Integer.parseInt(x.group().substring(2), 16))))
.collect(Collectors.joining());
System.out.println(ss);
UNICODE_ESCAPE.matcher(s).results() returns the stream of MatcherResult.
x.group().substring(2) extracts hexadecimal part "xxxx" from "\\uxxxx".
Integer.parseInt(..., 16) converts it to an integer value that is a code point.
Caracter.toChars() converts it to an array of char.
new String(...) converts it to an String. And .collect(Collectors.joining()) concatenates the all of them.
output:
深圳
Going by this output:
\深\圳
you actually have two unicode characters each preceded by one backslash.
In a Java string literal, that would look like this:
String s = "\\\u6df1\\\u5733";
If you want to remove the backslashes (\\) and leave the unicode character codes (e.g. \u6df1), then you just need replace.
String ss = s.replace("\\", "");
replaceAll won't work for this, because it requires a regular expression as its first argument.

How to remove characters from String Value?

I am storing below number as a string. How can I remove the first three characters & last one character from the string?
String No = "00098000002208";
The easiest and probably fastest way would be to just use the base string function substring:
String input = "00034000004409";
String output = input.substring(3, input.length()-1);
We could also try doing a regex replacement:
String output = input.replaceAll("^.{3}(.*).$", "$1");

Spilt string and match end of string with enum values

I have one string which i need to divide into two parts using regex
String string = "2pbhk";
This string i need to divide into 2p and bhk
More over second part should always be bhk or rk, as strings can be one of 1bhk, 5pbhk etc
I have tried
String pattern = ([^-])([\\D]*);
You can use the following regex "(?=bhk|rk)" with split.
str.split("(?=bhk|rk)");
This will split it if there is one of bhk or rk.
This should do the trick:
(.*)(bhk|rk)
First capture holds the "number" part, and the second bhk OR rk.
Regards
String string = "2pbhk";
String first_part, second_part = null;
if(string.contains("bhk")){
first_part = string.substring(0, string.indexOf("bhk"));
second_part = "bhk";
}
else if(string.contains("rk")){
first_part = string.substring(0, string.indexOf("rk"));
second_part = "rk";
}
Try the above once, not using regex but should work.
In case you are looking to split strings that end with rk or bhk but not necessarily at the end of the string (i.e. at the word boundaries), you need to use a regex with \\b:
String[] arr = "5ddddddpbhk".split("(?=(?:rk|bhk)\\b)");
System.out.println(Arrays.toString(arr));
If you want to allow splitting inside a longer string, remove the \\b.
If you only split individual words, use $ instead of \\b (i.e. end of string):
(?=(?:rk|bhk)$)
Here is my IDEONE demo

Replace character with a particular String in Java

I have a program which should replace a alternate characters in the string with a new string. Lets say I have...
String s1 = "JAVAJAVA";
String s2 = "VA";
Output:
VAAVAAVAAVAA
Character in the each alternate index of s1 should be replaced with s2. I've tried using StringBulider but I'm not able to proceed further with it. Can someone help me out on this please. thanks
Try this:
s1 = s1.replaceAll(".(.)", s2+"$1");
Explanation: Regular Expression ".(.)" matches every 2 characters. The second char is "remembered" (brackets), so you can re-use it in the replacement part ($1):
If you want to go other way than REGEX other simple solution can be, though regex one should be preferred one
1) Split String to char array with String class toCharArray() function
2) Replace the new character at alternate position by running loop
3) Convert back array to string with new String(charArray)
have you tried string replace function?
here are some examples: http://javarevisited.blogspot.ch/2011/12/java-string-replace-example-tutorial.html
You can use it like this:
String newString = s1.replace("J", s2);

Split String With Some Constraints In 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

Categories