Replacing more than one character in a String - java

I am printing an array, but I only want to display the numbers. I want to remove the brackets and commas from the String (leaving only the digits). So far, I have been able to remove the commas but I was looking for a way add more arguments to the replaceAll method.
How can I remove the brackets as well as the commas?
cubeToString = Arrays.deepToString(cube);
System.out.println(cubeToString);
String cleanLine = "";
cleanLine = cubeToString.replaceAll(", ", ""); //I want to put all braces in this statement too
System.out.println(cleanLine);
The output is:
[[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5]]
[[0000][1111][2222][3333][4444][5555]]

You can use the special characters [ and ] to form a pattern, and then \\ to escape the [ and ] (from your input) like,
cleanLine = cubeToString.replaceAll("[\\[\\]\\s,]", "");
or replace everything not a digit. Like,
cleanLine = cubeToString.replaceAll("\\D", "");

What you are doing is effectively using Java like you use a scripting language.
In this case, it happens to work well because your arrays only contain numbers and you don't have to worry about escaping characters that may also appear inside your array elements.
But it's still not efficient or Java-like to be converting strings several times, one of them with regular expressions (replaceAll), to get to your end-result.
A nicer and more efficient approach is to directly build the string that you need without any comma's or square brackets:
public static void main(String[] args) throws Exception {
int[][] cube = { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 },
{ 5, 5, 5, 5 } };
StringBuilder builder = new StringBuilder();
for (int[] r : cube) {
for (int c : r) {
builder.append(c);
}
}
String cleanLine = builder.toString();
System.out.println(cleanLine);
}
Output:
000011112222333344445555

Related

How to get number from string array in java

i have a string like String[] str = {"[5, 2, 3]","[2, 2, 3, 10, 6]"} and i need to take numbers to add into an integer list.
i tried to split first index into numbers to see if it will work, looks like:
String[] par = str[0].split("[, ?.#]+");
After the split i tried to see what array i get:
for(String a: par)
System.out.println(a);
But when i wrote that code i get an array like this:
[5
2
3]
So, how can i get rid of this square brackets?
Instead of your current pattern, I would use \\D+ which will split on one or more non-digits. Add a guard for the empty string too. Something like
String[] str = { "[5, 2, 3]", "[2, 2, 3, 10, 6]" };
for (String par : str) {
for (String t : par.split("\\D+")) {
if (t.isEmpty()) {
continue;
}
System.out.println(Integer.parseInt(t));
}
}
Outputs
5
2
3
2
2
3
10
6

java use regular expression in String.split to prepare json argument

I have a csv file which contain this type of document:
{""cast_id"": 10, ""character"": ""Mushu (voice)"", ""credit_id"": ""52fe43a09251416c75017cbb"", ""gender"": 2, ""id"": 776, ""name"": ""Eddie Murphy"", ""order"": 0}, {""cast_id"": 62, ""character"": ""[Singing voice]"", ""credit_id"": ""597a65c8925141233d0000bb"", ""gender"": 2, ""id"": 18897, ""name"": ""Jackie Chan"", ""order"": 1}, {""cast_id"": 16, ""character"": ""Mulan (voice)"", ""credit_id"": ""52fe43a09251416c75017cd5"", ""gender"": 1, ""id"": 21702, ""name"": ""Ming-Na Wen"", ""order"": 2}
I used this regular expression first to change quadruple quote to double quote:
String newResult = result.replaceAll("\"{2}", "\"");
Then I use this regular expression to split this string:
String[] jsonResult = newResult.split(", (?![^{]*\\})");
However, it seperates the string into this:
{"cast_id": 10, "character": "Mushu (voice)", "credit_id": "52fe43a09251416c75017cbb", "gender": 2, "id": 776, "name": "Eddie Murphy", "order": 0}
{"cast_id": 62
"character": "[Singing voice
something else then
{"cast_id": 16, "character": "Mulan (voice)", "credit_id": "52fe43a09251416c75017cd5", "gender": 1, "id": 21702, "name": "Ming-Na Wen", "order": 2}
So my regular expression failed when it meets square brackets [], can I have some help with this?
I tried to use http://www.regexplanet.com/advanced/java/index.html but I don't understand what I should put in option, replacement and input. How do I use this website?
Thanks
You are dealing with JSON data which has been saved as one column CSV file. :)
Quotes will be escaped with double quotes in CSV, so you could just use a CSV library to read your file. As I said, you should expect to get just one column - one value containing your JSON. Then you use a JSON library to parse your JSON.
=> you would not need to implement any parsing at all.
You should be looking for the pattern }, {
The regex: (?<=\}), (?=\{) does just that. Your regex will give a false positive if a } is missing at the end of the string.
(Tested with https://regex101.com/)
After that you can parse each string as JSON, use a library for that.
As others recommended, a parser would be a better solution than splitting yourself. Regular expressions run into limitations when you get nested brackets, for example. I used Google's Gson library, and tweaking your input slightly produced the desired split. The important step was to turn your input into a JSON array, otherwise the parser would fail after the first element:
// Pre-processed your input to remove the double double quotes
String input = "{'cast_id': 10, 'character': 'Mushu (voice)', 'credit_id': '52fe43a09251416c75017cbb', 'gender': 2, 'id': 776, 'name': 'Eddie Murphy', 'order': 0}, {'cast_id': 62, 'character': '[Singing voice]', 'credit_id': '597a65c8925141233d0000bb', 'gender': 2, 'id': 18897, 'name': 'Jackie Chan', 'order': 1}, {'cast_id': 16, 'character': 'Mulan (voice)', 'credit_id': '52fe43a09251416c75017cd5', 'gender': 1, 'id': 21702, 'name': 'Ming-Na Wen', 'order': 2}";
JsonArray array = new JsonParser().parse("[" + input + "]").getAsJsonArray();
for (int i = 0; i < array.size(); i++)
{
System.out.println(array.get(i));
}
Output:
{"cast_id":10,"character":"Mushu (voice)","credit_id":"52fe43a09251416c75017cbb","gender":2,"id":776,"name":"Eddie Murphy","order":0}
{"cast_id":62,"character":"[Singing voice]","credit_id":"597a65c8925141233d0000bb","gender":2,"id":18897,"name":"Jackie Chan","order":1}
{"cast_id":16,"character":"Mulan (voice)","credit_id":"52fe43a09251416c75017cd5","gender":1,"id":21702,"name":"Ming-Na Wen","order":2}

How do I convert a String to an String Array? [duplicate]

This question already has answers here:
How do I convert a String to an int in Java?
(47 answers)
Closed 7 years ago.
I'm reading from a file using Scanner, and the text contains the following.
[8, 3, 8, 2, 3, 4, 4, 4, 5, 8]
This was originally an integer Array that I had to convert to a String to be able to write in the file. Now, I need to be able to read the file back into java, but I need to be able to add the individual numbers together, so I need to get this String back into an array. Any help? Here's what I have:
File f = new File("testfile.txt");
try{
FileWriter fw = new FileWriter(f);
fw.write(Arrays.toString(array1));
fw.close();
} catch(Exception ex){
//Exception Ignored
}
Scanner file = new Scanner(f);
System.out.println(file.nextLine());
This prints out the list of numbers, but in a string. I need to access the integers in an array in order to add them up. This is my first time posting, let me know if I messed anything up.
You can use String#substring to remove the square brackets, String#split to split the String into an array, String#trim to remove the whitespace, and Integer#parseInt to convert the Strings into int values.
In Java 8 you can use the Stream API for this:
int[] values = Arrays.stream(string.substring(1, string.length() - 1)
.split(","))
.mapToInt(string -> Integer.parseInt(string.trim()))
.toArray();
For summing it, you can use the IntStream#sum method instead of converting it to an array at the end.
You don't need to read the String back in an Array, just use Regex
public static void main(String[] args) throws Exception {
String data = "[8, 3, 8, 2, 3, 4, 41, 4, 5, 8]";
// The "\\d+" gets the digits out of the String
Matcher matcher = Pattern.compile("\\d+").matcher(data);
int sum = 0;
while(matcher.find()) {
sum += Integer.parseInt(matcher.group());
}
System.out.println(sum);
}
Results:
86
List<Integer> ints = new ArrayList<>();
String original = "[8, 3, 8, 2, 3, 4, 4, 4, 5, 8]";
String[] splitted = original.replaceAll("[\\[\\] ]", "").split(",");
for(String s : splitted) {
ints.add(Integer.valueOf(s));
}

find all letters in String with regex

I know toCharArray() method but I am interested in regex. I have question for you about speed of two regex:
String s = "123456";
// Warm up JVM
for (int i = 0; i < 10000000; ++i) {
String[] arr = s.split("(?!^)");
String[] arr2 = s.split("(?<=\\G.{1})");
}
long start = System.nanoTime();
String[] arr = s.split("(?!^)");
long stop = System.nanoTime();
System.out.println(stop - start);
System.out.println(Arrays.toString(arr));
start = System.nanoTime();
String[] arr2 = s.split("(?<=\\G.{1})");
stop = System.nanoTime();
System.out.println(stop - start);
System.out.println(Arrays.toString(arr2));
output:
Run 1:
3158
[1, 2, 3, 4, 5, 6]
3947
[1, 2, 3, 4, 5, 6]
Run 2:
2763
[1, 2, 3, 4, 5, 6]
3158
[1, 2, 3, 4, 5, 6]
two regex are doing the same job. Why the first regex is more faster than second one ? . Thanks for your answers.
I can never be 100% sure, but I can think of one reason.
(?!^) always fails or succeeds in one shot (one attempt), that is if it can't find the start-of-string which is just a single test.
As for (?<=\\G.{1}) (which is exactly equivalent to just (?<=\\G.)) it always involved two steps or two matching attempts.
\\G matches either at the start-of-string or at the end of previous match, and even when it is successful, the regex engine still has to try and match a single character ..
For example, in your string 123456, at the start of the string:
(?!^): fails immediately.
(?<=\\G.): \\G succeeds, but then it looks for . but can't find a character behind because this is the start-of-string so now it fails, but as you can see it attempted two steps versus one step for the previous expression.
The same goes for every other position in the input string. Always two tests for (?<=\\G.) versus a single test for (?!^).

Input from text file to array

The input will be a text file with an arbitrary amount of integers from 0-9 with NO spaces. How do I populate an array with these integers so I can sort them later?
What I have so far is as follows:
BufferedReader numInput = null;
int[] theList;
try {
numInput = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
int i = 0;
while(numInput.ready()){
theList[i] = numInput.read();
i++;
Obviously theList isn't initialized, but I don't know what the length will be. Also I'm not too sure about how to do this in general. Thanks for any help I receive.
To clarify the input, it will look like:
1236654987432165498732165498756484654651321
I won't know the length, and I only want the single integer characters, not multiple. So 0-9, not 0-10 like I accidentally said earlier.
Going for Collection API i.e. ArrayList
ArrayList a=new Arraylist();
while(numInput.ready()){
a.add(numInput.read());
}
You could use a List<Integer> instead of a int[]. Using a List<Integer>, you can add items as desired, the List will grow along. If you are done, you can use the toArray(int[]) method to transform the List into an int[].
1 . Use guava to nicely read file's 1st line into 1 String
readFirstLine
2 . convert that String to char array - because all of your numbers are one digit lengh, so they are in fact chars
3 . convert chars to integers.
4 . add them to list.
public static void main(String[] args) {
String s = "1236654987432165498732165498756484654651321";
char[] charArray = s.toCharArray();
List<Integer> numbers = new ArrayList<Integer>(charArray.length);
for (char c : charArray) {
Integer integer = Integer.parseInt(String.valueOf(c));
numbers.add(integer);
}
System.out.println(numbers);
}
prints: [1, 2, 3, 6, 6, 5, 4, 9, 8, 7, 4, 3, 2, 1, 6, 5, 4, 9, 8, 7, 3, 2, 1, 6, 5, 4, 9, 8, 7, 5, 6, 4, 8, 4, 6, 5, 4, 6, 5, 1, 3, 2, 1]

Categories