Split String by +-/* and keep all other special characters [duplicate] - java

This question already has answers here:
Split string at hyphen characters too
(3 answers)
Closed 7 years ago.
Hey guys I am trying to split a string that is a mathematical expression.
For example - 1.1234-345+43/23.546*34
I want to split by -+/* and keep all numbers.
I have tried this:
String[] newString = "242342.4242+424-32.545".split("[+-//*]");
But it does not work, it also splits by the . and it gives me 5 numbers in the array in the end, and it should give me 3 numbers.
The new string should look like this:
newString[0] = 242342.4242
newstring[1] = 424
newString[2] = 32.545

public static void main(String[] args) {
// Using | in pattern
// \\ for special character
String[] newString = "242342.4242+424-32.545".split("\\+|-|\\*"); // +|-|*
System.out.println(Arrays.toString(newString));
// Output
// [242342.4242, 424, 32.545]
// In the real world. You need to handle Space too
// so using this pattern
// \\s*(\\+|-|\\*)\\s*
String[] newString2 = "242342.4242 + 424 - 32.545".split("\\s*(\\+|-|\\*)\\s*");
System.out.println(Arrays.toString(newString2));
// Output
// [242342.4242, 424, 32.545] - No spaces
}

public class test
{
public static void main(String[] args)
{
String[] newString = "242342.4242+424-32.545".split("[-+*/]");
for (String s : newString)
{
System.out.println(s);
}
}
}

Related

Split() an expression with a break line in Java [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
Which method of java.lang.String should I use to split the string below into an array or collection of strings, the splitting being done with respect to the character of the line break?
String str="This is a string\nthis is the next line.\nHello World.";
I think that method is split().
String[] arrOfStr = str.split("\n", limit);
but I don't know what to put in the limit in order to follow the requirements.
I did that code:
public class Split {
public static void main(String[] args) {
String str="This is a string\nthis is the next line.\nHello World.";
String[] arrOfStr = str.split("\n");
System.out.println(arrOfStr);
}
}
But the result is [Ljava.lang.String;#36baf30c
I don't understand.
You don't need to pass a limit to String#split if you want to split for all occurrences of \n. To show the contents of the array (instead of the reference), you can use Arrays.toString.
String str = "This is a string\nthis is the next line.\nHello World.";
String[] arrOfStr = str.split("\n");
System.out.println(Arrays.toString(arrOfStr));
Output:
[This is a string, this is the next line., Hello World.]
To see what the limit argument does, you can write a for-loop and observe the result like this:
String str = "This is a string\nthis is the next line.\nHello World.";
for (int limit = 0; limit < 4; limit++) {
String[] arrWithLimit = str.split("\n", limit);
System.out.println(limit + ": " + Arrays.toString(arrWithLimit));
}
Output:
0: [This is a string, this is the next line., Hello World.]
1: [This is a string
this is the next line.
Hello World.]
2: [This is a string, this is the next line.
Hello World.]
3: [This is a string, this is the next line., Hello World.]
You can see that the parameter limits the amount of splits being applied. 0 considers all occurrences (same as without limit). With 1 there is only 1 element in arrWithLimit and with 2 there are 2 elements.
Iterate through the array that you created from the split method.
public static void main(String[] args) {
String str="This is a string\nthis is the next line.\nHello World.";
String[] arrOfStr = str.split("\n");
for(int i = 0; i < arrOfStr.length; i++){
System.out.println(arrOfStr[i]);
}
}
Also another way to look at the contents is to use Arrays.deepToString() such as:
System.out.println(Arrays.deepToString(arrOfStr));
This results in the following outputs:
for loop iterating output:
This is a string
this is the next line.
Hello World.
deepToString output:
[This is a string, this is the next line., Hello World.]
String str="This is a string\nthis is the next line.\nHello World.";
String ab[]= str.split("[\\r\\n]+");
Arrays.stream(ab).forEach(abc -> System.out.println(abc + " "));
Replace in your code:
System.out.println(arrOfStr); // it is printing the memory location since the `toString`
// method is implemented in this way
by:
for(int i = 0; i<arrOfStr.length; i++)
System.out.println(arrOfStr[i]);
}

Regex for splitting word / (slash) word [duplicate]

This question already has answers here:
Split the string on forward slash
(4 answers)
Closed 2 years ago.
I really need a regex expert:
I need a regex expression (in java) for splitting this examples:
Hello/World (word/word) => Hello,World
Hello/12 (word/number) => Hello,12
15/Hello (number/word) => 15,Hello
12/17 (number/number) => 12/17 (Do not split)
Update:
This is what I tried but it also mark the number/number option
https://regex101.com/r/zZ9nO5/2
Thanks
It might not be the most elegant solution but for your requirement you can do it like that:
(([a-zA-Z]+?)/([a-zA-Z]+))|(([a-zA-Z]+?)/([\d]+))|(([\d]+?)/([a-zA-Z]+))
It's a check for word / word, word / number and number / word
replace with the corresponding groups found \2\5\8,\3\6\9
A simple java program for that would be:
public static void main(String[] args) {
String[] stringArray=new String[]{"Hello/World","Hello/12","15/Hello","12/17"};
for(String s:stringArray) {
System.out.println(s.replaceAll("(([a-zA-Z]+?)/([a-zA-Z]+))|(([a-zA-Z]+?)/([\\d]+))|(([\\d]+?)/([a-zA-Z]+))", "$2$5$8,$3$6$9"));
}
}
Result is:
Hello,World
Hello,12
15,Hello
12/17
Slightly different approach, but you could check the characters in the String to see that they all are either a number or a forward slash, and then split if necessary:
public static void main(String[] args) {
String[] strArray = new String[]{"Hello/World", "Hello/12", "15/Hello", "12/17"};
for(String str: strArray){
if(checkIfValid(str)){
System.out.println(str);
}
else{
System.out.println(str.replace("/", ","));
}
}
}
public static boolean checkIfValid(String str) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != '/') {
return false;
}
}
return true;
}
Output:
Hello,World
Hello,12
15,Hello
12/17
This might help if Hello12/15 is not supposed to be split.
A little more context would be nice but as I understand it, you get a string with a single '/' in the middle and you either replace the '/' with ',' or you dont if it has numbers on both sides.
So i would do something like this:
public class MyClass {
public static void main(String args[]) {
String mystring = "12/25";
if(!mystring.matches("^\\d+\\/\\d+$"))
mystring = mystring.replace("/", ",");
System.out.println(mystring);
}
}
If that is what you wanted to do here, then I belive its less complicated and also quicker than a big regex destinguishing between all 4 cases.

Split a String using split function to count number of "that" [duplicate]

This question already has answers here:
Find the Number of Occurrences of a Substring in a String
(27 answers)
Closed 5 years ago.
String str = "ABthatCDthatBHthatIOthatoo";
System.out.println(str.split("that").length-1);
From this I got 4. that is right but if last that doesn't have any letter after it then it shows wrong answer '3' as in :
String str = "ABthatCDthatBHthatIOthat";
System.out.println(str.split("that").length-1);
I want to count the occurrence of "that" word in given String.
You could specify a limit to account for the final 'empty' token
System.out.println(str.split("that", -1).length-1);
str.split("that").length doesn't count the number of 'that's . It counts the
number of words that have 'that' in between them
For example-
class test
{
public static void main(String args[])
{
String s="Hi?bye?hello?goodDay";
System.out.println(s.split("?").length);
}
}
This will return 4, which is the number of words separated by "?".
If you return length-1, in this case, it will return 3, which is the correct count of the number of question marks.
But, what if the String is : "Hi????bye????hello?goodDay??"; ?
Even in this case, str.split("?").length-1 will return 3, which is the incorrect count of the number of question marks.
The actual functionality of str.split("that //or anything") is to make a String array which has all those characters/words separated by 'that' (in this case).The split() function returns a String array
So, the above str.split("?") will actually return a String array : {"Hi,bye,hello,goodDay"}
str.split("?").length is returning nothing but the length of the array which has all the words in str separated by '?' .
str.split("that").length is returning nothing but the length of the array which has all the words in str separated by 'that' .
Here is my link for the solution of the problem link
Please tell me if you have any doubt.
Find out position of substring "that" using lastIndexOf() and if its at last position of the string then increment the cout by 1 of your answer.
Try this
String fullStr = "ABthatCDthatBHthatIOthatoo";
String that= "that";
System.out.println(StringUtils.countMatches(fullStr, that));
use StringUtils from apache common lang, this one https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/src-html/org/apache/commons/lang/StringUtils.html#line.170
I hope this would help
public static void main(String[] args) throws Exception
{ int count = 0;
String str = "ABthatCDthatBHthatIOthat";
StringBuffer sc = new StringBuffer(str);
while(str.contains("that")){
int aa = str.indexOf("that");
count++;
sc = sc.delete(aa, aa+3);
str = sc.toString();
}
System.out.println("count is:"+count);
}

Java, how to check if a string contains a digit? [duplicate]

This question already has answers here:
Check and extract a number from a String in Java
(16 answers)
Closed 5 years ago.
how do I check if a string contains a digit?
public static void main(String[] args)
{
s1 = "Hello32"; //should be true`enter code here`
s2 = "He2llo"; //should be true
s3 = "Hello"; //should be false
}
With a regex you could search at least a digit among any (zero or more) characters:
boolean hasDigit = s1.matches(".*\\d+.*");
Check this it might help you
String regex = "\\d+";
System.out.println("abc45hdg".matches(regex));
In java
public boolean containsNumber(String string)
{
return string.matches(".*\\d+.*");
}

How can I change an all caps string to capitalize on first letter and then first letter following each space? (Java) [duplicate]

This question already has answers here:
How to capitalize the first character of each word in a string
(51 answers)
Closed 6 years ago.
Let's say we have a string in java:
String str = "ALL CAPS MATE";
How can I change it so that it looks like this but for any word:
String result = "All Caps Mate";
Is there a String method similar to .toUpperCase() or .toLowerCase()? If there is, I can't seem to find it.
I would appreciate a string method solution.
Thanks.
The apache libraries contain some methods to handle this as mentioned by B'bek Shakya and a comment, but if you are looking for a straight native Java solution you would do this as Bald Banta mentioned in the comments.
Here is a code example using streams:
public static void main(String[] args) {
String input = "fOo bar";
String transformed = Arrays.stream(input.toLowerCase()
.split(" "))
.map(String::toCharArray)
.map(arr -> {
arr[0] = Character.toUpperCase(arr[0]);
return arr;
})
.map(String::valueOf)
.collect(Collectors.joining(" "));
System.out.println(transformed);
}
And the same thing using a more common loop idiom:
public static void main(String[] args) {
String input = "fOo bar";
String[] words = input.toLowerCase().split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
char[] word = words[i].toCharArray();
word[0] = Character.toUpperCase(word[0]);
if (i != 0) {
sb.append(" ");
}
sb.append(String.valueOf(word));
}
System.out.println(sb.toString());
}
I think this would solve your problem by using apache library for more information
org.apache.commons.lang3.text.WordUtils
String result= WordUtils.capitalizeFully(str);
for more complex one look at this link
and i think your question is already answer here
The WordUtils class from org.apache.commons.lang3.text has a static capitalizeFully method, which does what you require. You'll need the commons lang3 jar in your classpath.
import org.apache.commons.lang3.text.WordUtils;
WordUtils.capitalizeFully(input);

Categories