Java string -> two numbers - java

The operation I'm hoping to perform is to go from:
String "32.63578..."
to:
float 32.63
long 578... //where '...' is rest of string
Something like the following in Python:
split = str.find('.')+2
float = str[:split]
long = str[split:]
I'm new to Java, so I began by trying to look up equivalents, however it seems like a more convoluted solution than perhaps a regex would be? Unless there's more similar functions to python than splitting into a char array, and repeatedly iterating over?

Use indexOf and substring methods:
String str = "32.63578";
int i = str.indexOf(".") + 3;
String part1 = str.substring(0, i); // "32.63"
String part2 = str.substring(i); // "578"
float num1 = Float.parseFloat(part1); // 32.63
long num2 = Long.parseLong(part2); // 578

Regular expression alternative:
String str = "32.63578";
String[] parts = str.split("(?<=\\.\\d{2})");
System.out.println(parts[0]); // "32.63"
System.out.println(parts[1]); // "578"
About the regular expression used:
(?<=\.\d{2})
It's positive lookbehind (?<=...). It matches at the position where is preceded by . and 2 digits.

You can use the split method in String if you want to cleanly break the two parts.
However, if you want to have trailing decimals like in your example, you'll probably want to do something like this:
String str = "32.63578...";
String substr1, substr2;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == '.')
{
substr1 = str.substring(0, i + 3);
substr2 = str.substring(i + 3, str.length());
break;
}
}
//convert substr1 and substr2 here

String s ="32.63578";
Pattern pattern = Pattern.compile("(?<Start>\\d{1,10}.\\d{1,2})(?<End>\\d{1,10})");
Matcher match = pattern.matcher(s);
if (match.find()) {
String start = match.group("Start");
String ending = match.group("End");
System.out.println(start);
System.out.println(ending);
}

Related

Get the substring before the middle occurrence of a separator in java

I have a string bac/xaz/wed/rgc. I want to get the substring before and after the middle / in the string.
I don't find the solution with string split. how to achieve this? I am not sure if I have to use regex and split the string.
public static void main(String ...args) {
String value = "bac/xaz/wed/rgc/wed/rgc";
// Store all indexes in a list
List<Integer> indexList = new ArrayList<>();
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) == '/') {
indexList.add(i);
}
}
// Get the middle index from the list, works for odd number only.
int middleIndex = indexList.get(indexList.size() / 2);
System.out.println("First half: " + value.substring(0, middleIndex));
System.out.println("Second half: " + value.substring(middleIndex + 1));
}
Not an elegant solution, but it can handle as much '/' you gave it, as long as the total number of '/' is odd number.
Using an ArrayList might be overkill, but it works XD.
You can use split function to achieve that, using / as a delimiter:
String str = "bac/xaz/wed/rgc";
String[] arr = str.split('/');
You'll get an array of 4 strings: ["bac", "xaz", "wed", "rgc"].
From then on, you can retrieve the one that you want. If I understand well, you are interested in the elements 1 and 2:
String before = arr[1];
String after = arr[2];
If you meant to get the whole sub-string before the middle /, you can still concatenate the first two strings:
String strbefore = arr[0] + arr[1];
Same goes for the rest:
String strafter = arr[2] + arr[3];
here is a simple solution
String str = "bac/xaz/wed/rgc";
int loc = str.indexOf("/",str.indexOf('/')+1);
String str1 = str.substring(0,loc);
String str2 = str.substring(loc+1,str.length());
System.out.println(str1);
System.out.println(str2);
bac/xaz
wed/rgc

How to use regex to split a string containing numbers and letters in java

My task is splitting a string, which starts with numbers and contains numbers and letters, into two sub-strings.The first one consists of all numbers before the first letter. The second one is the remained part, and shouldn't be split even if it contains numbers.
For example, a string "123abc34de" should be split as: "123" and "abc34de".
I know how to write a regular expression for such a string, and it might look like this:
[0-9]{1,}[a-zA-Z]{1,}[a-zA-Z0-9]{0,}
I have tried multiple times but still don't know how to apply regex in String.split() method, and it seems very few online materials about this. Thanks for any help.
you can do it in this way
final String regex = "([0-9]{1,})([a-zA-Z]{1,}[a-zA-Z0-9]{0,})";
final String string = "123ahaha1234";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
matcher.group(1) contains the first part and matcher.group(2) contains the second
you can add it to a list/array using these values
You can use a pretty simple pattern : "^(\\d+)(\\w+)" which capture digits as start, and then when letters appear it take word-char
String string = "123abc34de";
Matcher matcher = Pattern.compile("^(\\d+)(\\w+)").matcher(string);
String firstpart = "";
String secondPart = "";
if (matcher.find()) {
firstpart = matcher.group(1);
secondPart = matcher.group(2);
}
System.out.println(firstpart + " - " + secondPart); // 123 - abc34de
This is not the correct way but u will get the result
public static void main(String[] args) {
String example = "1234abc123";
int index = 0;
String[] arr = new String[example.length()];
for (int i = 0; i < example.length(); i++) {
arr = example.split("");
try{
if(Integer.parseInt(arr[i]) >= 0 & Integer.parseInt(arr[i]) <= 9){
index = i;
}
else
break;
}catch (NumberFormatException e) {
index = index;
}
}
String firstHalf = example.substring(0,Integer.parseInt(arr[index])+1);
String secondHalf = example.substring(Integer.parseInt(arr[index])+1,example.length());
System.out.println(firstHalf);
System.out.println(secondHalf);
}
Output will be: 1234 and in next line abc123

Java Regular Expression : Need Simpler Solution

I am new to regular expressions. I have a string named encryptId (does not contain |) and I want to append the | character after every 20 characters of this string, using the encryptId.replace/replaceAll(Regex,Pattern) function in Java. But it should never have \ at the end of the string.
Thanks for your help.
EDIT:
The reason I want to use replace and replaceAll functions particularly is because I have to use that in velocity template mananger. And there we can use common String functions but can't write whole java code.
My current solution is shown below
encryptId = encryptId.replaceAll("(.{20})","$1|");
if(encryptId.charAt(encryptId.length() - 1)=='|') {
encryptId = encryptId.substring(0,encryptId.length()-1);
}
I need to get rid of this if statement so that It would be just a string function.
You asked how to do it with replaceAll: I say don't. Regular expressions are not always the best approach to string manipulation problems.
You can efficiently build the new string by taking 20 character blocks from encryptId and appending them to a StringBuilder, optionally appending the pipe if it will not be at the end of the string:
String method(String encryptId) {
StringBuilder sb = new StringBuilder(encryptId.length() + encryptId.length() / 20);
for (int i = 0; i < encryptId.length(); i += 20) {
int end = Math.min(i + 20, encryptId.length());
sb.append(encryptId, i, end);
if (end != encryptId.length()) {
sb.append('|');
}
}
return sb.toString();
}
You can use String.toCharArray:
String s = "..."; //your string
int i = 0;
StringBuilder res = new StringBuilder("");
for (char c : s.toCharArray()){
res.append(c);
i++;
if (i % 20 == 0 && i != s.length()){
res.append("|");
}
}
System.out.println(res.toString());
res will have your first String with an | every 20 characters but not at the end of the String.
This can be done via regular expressions as follows
static String enterADelimiter(String str, String delimiter, int after) {
String regex = "(.{" + after +"})(?!$)";
String replacement = "$1" + delimiter;
return str.replaceAll(regex, replacement);
}
Just use
enterADelimiter(yourString, "|", 20)
This will return correct solution. Explantion
( Start group 1
. Match Anything
{after} after times
) End group 1
(?!$) Don't match if at end of String
Regex may complicate things more. You can also try to use StringBuilder for this:
String encryptId = "test";
StringBuilder builder = new StringBuilder(encryptId);
int insertAfter = 20;
for(int i = encryptId.length(); i > 0 ; i--) {
if (i % insertAfter == 0 && i != encryptId.length()) {
builder.insert(i, "|");
}
}

how to get sub string after four spaces in the given string?

I have string like "align is going to school sad may me". I want to get the sub string after the four spaces. The String will be entered at run time. can anyone suggest me to find the Sub String after some set of spaces......
String st = "align is going to school sad may me";
int i = 0;
String [] strings = new String [15];
StringTokenizer stringTokenizer = new StringTokenizer (st, " ");
while (stringTokenizer.hasMoreElements ())
{
strings [i]= (String)stringTokenizer.nextElement ();
i++;
}
System.out.println ("I value is" + i);
for (int j=4; j<i; j++)
{
System.out.print (strings[j] + " ");
}
I've tried this one and it's working can you please suggest me simple method to find the Sub string after some set of spaces.
st = st.replaceAll("^(\\S*\\s){4}", "");
^ indicates that we remove only from the first character of the string.
\s is any white space. It would also remove, for example, tabulations.
\S is any non white space character.
* means any number of occurrences of the character.
So, \S* is any number of non white space characters before the white space.
{4} is obviously because you want to remove 4 white spaces.
You could also use:
st = st.replaceFirst("(\\S*\\s){4}", "");
which is the same but you don't need the ^.
In case the input string could have less than 4 white spaces:
st = st.replaceAll("^(\\S*\\s){1,4}", "");
would return you the last word of the string, only if the string doesn't end on a white space. You can be sure of that if you call trim first:
st = st.trim().replaceAll("^(\\S*\\s){1,4}", "");
What about using split?
st.split (" ", 5) [4]
It splits string by spaces, into not more than 5 chunks. Last chunk (with index 4) will contain everything after fourth space.
If it is not guaranteed that string contains 4 spaces, additional check is required:
String [] chunks = st.split (" ", 5);
String tail = chunks.length == 5 ? chunks [4] : null;
Tail will contain everything after fourth space or null, is there are less than four spaces in original string.
public static void main(String[] args) {
String st = " align is going to school sad may me ";
String trim = st.trim(); // if given string have space before and after string.
String[] splitted = trim.split("\\s+");// split the string into words.
String substring = "";
if (splitted.length >= 4) { // checks the condition
for (int i = 4; i < splitted.length; i++)
substring = substring + splitted[i] + " ";
}
System.out.println(substring);
}
This may be a overkill but it uses simple string operations (just str.indexOf(' ')).
If you needed for a school project or someting:
String str ="ada adasd dasdsa d adasdad dasasd";
int targetMatch = 4;
int offset = 0;
for(int i = 0 ; i < targetMatch; i++){
int position = str.indexOf(' ', offset);
if(position != -1){
System.out.println("position: "+ position);
offset = position+1;
}
}
String result = str.substring(offset);
System.out.println(result);
For real project... advanced regex would be better.
Here's a trivial and simple implementation that solves your problem:
String s = "I've tried this one and it's working can you please suggest";
int index = -1;
for (int i = 0; i < 4; i++) {
index = s.indexOf(' ', index + 1);
}
System.out.println(s.substring(index + 1));
It will fail if the string starts with a space or if it contains sequences of spaces. But it's a start.
Output: and it's working can you please suggest
public class MySplit {
public static void main(String agsp[]) {
String oldString = "roma h totti milan kaka juve love";
String[] allStrings = oldString.split("\\s");
String newString = "";
for (int i = 3; i < allStrings.length; i++)
newString = newString + " " + allStrings[i];
System.out.println(newString);
}
}
you can also make function like this
public String newSplit(String data, int index){
String[] allStrings = data.split("\\s");
String newString = "";
for (int i = index; i < allStrings.length; i++)
newString = newString + " " + allStrings[i];
return newString
}
The simple way using this piece of code
String thisString="Hello world go to kashmir";
String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
String first = parts[3];//"hello"
String second = parts[4];//"World"

Regex for formatting binary number with spaces every 4 characters, from right to left in Java

I'm writing a binary/decimal/hexadecimal converter for Android and am trying to format a String in Java with a regex that will add a space to every four characters from right to left.
This code works from left to right, but I am wondering if there is a way I can reverse it.
stringNum = stringNum.replaceAll("....", "$0 ");
Maybe instead of regex use StringBuilder like this
String data = "abcdefghij";
StringBuilder sb = new StringBuilder(data);
for (int i = sb.length() - 4; i > 0; i -= 4)
sb.insert(i, ' ');
data = sb.toString();
System.out.println(data);
output:
ab cdef ghij
In C# you would do something like Regex.Replace("1234567890", ".{4}", " $0", RegexOptions.RightToLeft).
Unfortunately, in Java you can't.
As Explossion Pills suggested in a comment, you could reverse the string, apply the regex, and reverse it again.
Another solution could be to take the last N numbers from your string, where N is divisible by 4. Then you can apply the replacement successfully, and concatenate the remaining part of the string at the begining.
String str = "0123456789ABCDE";
// Use a StringBuffer to reverse the string
StringBuffer sb = new StringBuffer(str).reverse();
// This regex causes " " to occur before each instance of four characters
str = sb.toString().replaceAll("....", "$0 ");
// Reverse it again
str = (new StringBuffer(str)).reverse().toString();
System.out.println(str);
For me the best practice was to start from the beginning of the string to the end:
String inputString = "1234123412341234";
int j = 0;
StringBuilder sb = new StringBuilder(inputString);
for (int i = 4; i < kkm.getFiscalNumber().length(); i += 4) {
sb.insert(i + j, ' ');
j++;
}
String result = sb.toString(); // 1234 1234 1234 1234

Categories