Splitting a Decimal Value(as String ) using java - java

I am converting a Decimal number to string and then i am splitting the number(String) using the .(Dot) operator.
For Ex:
double x=Math.sqrt(17);//4.12425325
String str=String.valueOf(x);
String ar[]=str.split(".");//But its not getting splitted.
But the String is not getting splitted into String Array ar[].

escape the . in split()
String ar[]=str.split("\\.");
argument to split() is a regex and . has a special meaning in regex ,so to match a literal . , you need to escape it.

Split() accepts a Regex as an argument. So, we need to escape the '.' here as '.' means any character in Regex, e.g.:
String s = "123.456";
String[] split = s.split("\\.");
System.out.println(Arrays.toString(split));

An alternative approach to get the whole number portion and the decimal portion.
String num = "123.45";
System.out.println( num.substring( 0, num.indexOf(".") ) ); // prints whole number part
System.out.println( num.substring( num.indexOf(".") + 1) ); // prints decimal part
If you are interested in just the contents of both the decimal and the whole number portions, this method doesn't involve using an array.

Related

Match a string in java replace it and get the integer from it

I am trying to find and replace a part of the string which contains an integer.
String str = "I <FS:20>am in trouble.</FS>";
I need to replace and
for /FS I am using
str = str.replace("</FS>", "\\fs0");
I am not sure how to approach the FS:20 because the 20 is a variable and in some cases might be a different number which means that I need to somehow the int part.
Input :
"I FS:20 am in trouble.";
Output :
"I \fs20 am in trouble.";
but 20 is not a fixed variable so I can't hardcode it
One way to do it is to make two replacements:
str = str.replaceAll("</FS>", "");
str = str.replaceAll("<FS:(\\d+)>", "\\\\fs$1");
System.out.println(str);
Output:
I \fs20am in trouble.
The first replacement just removes </FS> from the string.
The second replacement makes use of a RegEx pattern <FS:(\d+)>.
The RegEx pattern matches the literal characters <FS: followed by one or more digits, which it stores in group 1 (\d+), finally followed by the character >
The value stored in group 1 can be used in the replacement string using $1, so \\\\fs$1 will be a backslash \ followed by fs followed by the contents of group 1 (\d+), in this case 20.
The numbers matched by \d+ are stored in group 1, accessed using $1
If you can use your variable that is 20 in described case.
Integer yourVariable=20;
String str = "I <FS:20>am in trouble.</FS>";
str = str.replace("<FS:"+yourVariable+">", "\\fs0");

Splitting characters

My characters is "!,;,%,#,**,**,(,)" which get from XML. when I split it with ',', I lost the ','.
How can I do to avoid it.
I have already tried to change the comma to '&#002C', but it does not work.
Thre result I want is "!,;,%,#,,,(,)", but not "!,;,%,#,,(,)"
String::split use regex so you can split with this regex ((?<!,),|,(?!,)) like this :
String string = "!,;,%,#,,,(,)";
String[] split = string.split("((?<!,),|,(?!,))");
Details
(?<!,), match a comma if not preceded by a comma
| or
,(?!,) match a comma if not followed by a comma
Outputs
!
;
%
#
,
(
)
If you are trying to extract all characters from string, you can do so by using String.toCharArray()[1] :
String str = "sample string here";
char[] char_array = s.toCharArray();
If you just want to iterate over the characters in the string, you can use the character array obtained from above method or do so by using a for loop and str.charAt(i)[2] to access the character at position i.
[1] https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray()
[2]https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt(int)
try this, this could be help full. First I replaced the ',' with other string and do split. After complete other string replace with ','
public static void main(String[] args) {
String str = "!,;,%,#,**,**,(,)";
System.out.println(str);
str = str.replace("**,**","**/!/**");
String[] array = str.split(",");
System.out.println(Arrays.stream(array).map(s -> s.replace("**/!/**", ",")).collect(Collectors.toList()));
}
out put
!,;,%,#,**,**,(,)
[!, ;, %, #, ,, (, )]
First, we need to define when the comma is an actual delimiter, and when it is part of a character sequence.
We need to assume that a sequence of commas surrounded by commas is an actual character sequence we want to capture. It can be done with lookarounds:
String s = "!,;,,,%,#,**,**,,,,(,)";
List<String> list = Arrays.asList(s.split(",(?!,)|(?<!,),"));
This regular expression splits by a comma that is either preceded by something that is not a comma, or followed by something that is not a comma.
Note that your formatting string, that is, every character sequence separated by a comma, is a bad design, since you require both the possibility to use a comma as sequence, and the possibility to use multiple characters to be used. That means you can combine them too!
What, for example, if I want to use these two character sequences:
,
,,,,
Then I construct the formatting string like this: ,,,,,,. It is now unclear whether , and ,,,, should be character sequences, or ,, and ,,,.

splits strings in java in different manner

I am very new to java. i want to splits the string into following manner.
suppose i have given a string input like sample 1 jayesh =10 vyas =13 harshit=10; and so on as a input
sample 2: harsh=2, vyas=5;
now i want to store jayesh, vyas, harshit from sample 1 and harsh , vyas from sample 2(all this type of strings which are just before the assignment operator) into string or char array.
so can anyone please tell me about that how to do this in java. i know about split method in java, but in this case there are multiple strings i have to store.
you can use =\\d+;? regex
=\\d+;? match = and as many digits with ; as optional
String s="jayesh =10 vyas =13 harshit=10;";
String[] ss=s.split("=\\d+;?");
System.out.println(Arrays.toString(ss));
output
[jayesh , vyas , harshit]
To extend it further you can use \\s*=\\d+[,;]?\\s*
\\s* : match zero or more spaces
[,;]? match any character mention in the list as optional
but if you want to avoid any special character after digits then use
\\s*=\\d+\\W*" :
\\s*= : match zero or more spaces and = character
\\d+ : match one or more digits
\W* : match zero or more non-word character except a-zA-z0-9_
String s="harsh=2, vyas=5; vyas=5";
String s2 ="jayesh =10 vyas=13 harshit=10;";
String regex="\\s*=\\d+\\W*";
String[] ss=s.split(regex);
String[] ss2=s2.split(regex);
System.out.println(Arrays.toString(ss));
System.out.println(Arrays.toString(ss2));
output
[harsh, vyas, vyas]
[jayesh, vyas, harshit]
Note : Space after , is added for formatting by the Arrays.toString function though there is no space in the ss and ss2 array elements.
For Hashset use
Set<String> mySet = new HashSet<String>(Arrays.asList(ss));
you can use replaceAll() to get the expected results
String stringToSearch = "jayesh =10 vyas =13 harshit=10;";
stringToSearch = stringToSearch.replaceAll("=\\d+;?","");
System.out.println(stringToSearch);
output:
jayesh vyas harshit

cant make this delimiter work, java split

I need help making a delimiter for multiple characters
I need a String delimiter for
these characters
( ) " ; : , ? ! .
I've tried:
private String delimiter = "()\":;,?!.";
private String delimiter = "[()\":;,?!.]";
private String delimiter = "\\(\\)\"\\:\\;\\,\\?\\!\\.";
Seems I can only make them work one at a time..
Any insight is greatly appreciated.
If it matters this is how its going into array:
foo = line.split(delim);
If you want to split on any of those characters, you can separate each one with an alternation: |. Otherwise, the string will only be split when all of those characters are present.
String delimiter = "\\(|\\)|\"|\\:|\\;|\\,|\\?|\\!|\\.";
Also, you're unnecessarily escaping a few characters, this would also work:
String delimiter = "\\(|\\)|\"|:|;|,|\\?|!|\\.";
Almost there with nr. 3
#Test
public void delim() {
String delimiter = "[\\(\\)\"\\:\\;\\,\\?\\!\\.]";
String[] split = "Hello(World)How:are;You;doing,today?You!sir.I mean"
.split(delimiter);
System.out.println(Arrays.toString(split));
}
Output
[Hello, World, How, are, You, doing, today, You, sir, I mean]
You missed the square brackets.
To avoid all the quoting you may use Pattern#quote
String delimiter = "[" + Pattern.quote("()\":;,?!.") + "]";
Returns a literal pattern String for the specified String.
This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.
Metacharacters or escape sequences in the input sequence will be given no special meaning.
| is required between:
delimiter = "\\(|\\)|\"|:|;|,|\\?|!|\\."

having trouble with arrays and maybe split

String realstring = "&&&.&&&&";
Double value = 555.55555;
String[] arraystring = realstring.split(".");
String stringvalue = String.valueof(value);
String [] valuearrayed = stringvalue.split(".");
System.out.println(arraystring[0]);
Sorry if it looks bad. Rewrote on my phone. I keep getting ArrayIndexOutOfBoundsException: 0 at the System.out.println. I have looked and can't figure it out. Thanks for the help.
split() takes a regexp as argument, not a literal string. You have to escape the dot:
string.split("\\.");
or
string.split(Pattern.quote("."));
Or you could also simply use indexOf('.') and substring() to get the two parts of your string.
And if the goal is to get the integer part of a double, you could also simply use
long truncated = (long) doubleValue;
split uses regex as parameter and in regex . means "any character except line separators", so you could expect that "a.bc".split(".") would create array of empty strings like ["","","","",""]. Only reason it is not happening is because (from split javadoc)
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
so because all strings are empty you get empty array (and that is because you see ArrayIndexOutOfBoundsException).
To turn off removal mechanism you would have to use split(regex, limit) version with negative limit.
To split on . literal you need to escape it with \. (which in Java needs to be written as "\\." because \ is also Strings metacharacter) or [.] or other regex mechanism.
Dot (.) is a special character so you need to escape it.
String realstring = "&&&.&&&&";
String[] partsOfString = realstring.split("\\.");
String part1 = partsOfString[0];
String part2 = partsOfString[1];
System.out.println(part1);
this will print expected result of
&&&
Its also handy to test if given string contains this character. You can do this by doing :
if (string.contains(".")) {
// Split it.
} else {
throw new IllegalArgumentException("String " + string + " does not contain .");
}

Categories