Compare two strings of ints in java - java

I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10?
String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";

Looks like homework. So these steps you can follow:
Trim both strings
Convert both strings into ArrayList using space separator
Sort both arrays numerically
Compare both arrays

You can use Scanner.nextInt() to read numbers from the string, add them to a Set, and see if set1.equals(set2) is true.

I would not perform the comparison on the raw strings. Instead, first convert each String to a List<Integer> using String.split() and Integer.parseInt() on each result. Then sort() the lists into ascending order, and then it becomes very easy to compare them.

Try like this.
String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
Set<String> a = new HashSet<String> (Arrays.asList(one.trim().replaceAll("\\s*"," ").split(" ")));
Set<String> b = new HashSet<String> (Arrays.asList(two.trim().replaceAll("\\s*"," ").split(" ")));
boolean ret = (a.size() == b.size()) && a.containsAll(b);

You could tokenize/split the strings based on the spaces, then loop through the resulting tokens which would be the numbers themselves.

You split the strings on whitespace (using either String.split or StringTokenizer) and then convert each of the tokens into a number. Place all the numbers in string one into a HashSet. Do the same for string two. Now all you have to do is to check whether each entry in the first HashSet also occurs in the second one.

I would at first parse numbers as integers, put them to the set and compare them:
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class StringsCompare {
private static String one = "1 2 3 4 5 6";
private static String two = " 3 2 1 5 6 4 ";
public static void main(String[] args) {
StringsCompare sc = new StringsCompare();
System.out.println(sc.compare(one, two));
}
private boolean compare(String one, String two) {
SortedSet<Integer> setOne = getSet(one);
SortedSet<Integer> setTwo = getSet(two);
return setOne.equals(setTwo);
}
private SortedSet<Integer> getSet(String str) {
SortedSet<Integer> result = new TreeSet<Integer>();
StringTokenizer st = new StringTokenizer(str, " ");
while (st.hasMoreTokens()) {
result.add(Integer.valueOf(st.nextToken()));
}
return result;
}
}

Try to parse the strings in int.
Integer.parseInt(One).intValue() == Integer.parseInt(two).intValue()
I'm not sure what you're trying to do but my guess is that you'd better to use arrays.

Related

simple mathematical expression parsing

I try to write equals override function. I think I have written right but the problem is that parsing the expression. I have an array type of ArrayList<String> it takes inputs from keyboard than evaluate the result. I could compare with another ArrayList<String> variable but how can I compare the ArrayList<String> to String. For example,
String expr = "(5 + 3) * 12 / 3";
ArrayList<String> userInput = new ArrayList<>();
userInput.add("(");
userInput.add("5");
userInput.add(" ");
userInput.add("+");
userInput.add(" ");
userInput.add("3");
.
.
userInput.add("3");
userInput.add(")");
then convert userInput to String then compare using equals
As you see it is too long when a test is wanted to apply.
I have used to split but It splits combined numbers as well. like 12 to 1 and 2
public fooConstructor(String str)
{
// ArrayList<String> holdAllInputs; it is private member in class
holdAllInputs = new ArrayList<>();
String arr[] = str.split("");
for (String s : arr) {
holdAllInputs.add(s);
}
}
As you expect it doesn't give the right result. How can it be fixed? Or can someone help to writing regular expression to parse it properly as wanted?
As output I get:
(,5, ,+, ,3,), ,*, ,1,2, ,/, ,3
instead of
(,5, ,+, ,3,), ,*, ,12, ,/, ,3
The Regular Expression which helps you here is
"(?<=[-+*/()])|(?=[-+*/()])"
and of course, you need to avoid unwanted spaces.
Here we go,
String expr = "(5 + 3) * 12 / 3";
.
. // Your inputs
.
String arr[] = expr.replaceAll("\\s+", "").split("(?<=[-+*/()])|(?=[-+*/()])");
for (String s : arr)
{
System.out.println("Element : " + s);
}
Please see my expiriment : http://rextester.com/YOEQ4863
Hope it helps.
Instead of splitting the input into tokens for which you don't have a regex, it would be good to move ahead with joining the strings in the List like:
StringBuilder sb = new StringBuilder();
for (String s : userInput)
{
sb.append(s);
}
then use sb.toString() later for comparison. I would not advice String concatenation using + operator details here.
Another approach to this would be to use one of the the StringUtils.join methods in Apache Commons Lang.
import org.apache.commons.lang3.StringUtils;
String result = StringUtils.join(list, "");
If you are fortunate enough to be using Java 8, then it's even easier...just use String.join
String result = String.join("", list);
More details on this approach available here
this makes all the inputs into one string which can then be can be compared against the expression to see if it is equal
String x = "";
for(int i = 0; i < holdAllInputs.length; i++){
x = x + holdAllInputs.get(i);
}
if(expr == x){
//do something equal
}else{
//do something if not equal
}

How do I cut my sentence out to 4 sentences?

How do i cut this out to 4 sentences instead of 1.
i need to cut it out to 4 sentence and only 4 because my jList only accept 4 "persons"
in the JList it stands like this
name,2,2,2,2
Lars,1,4,2,5
Peter,5,3,2,1
Code:
List listOfPersonNames = jListpersons.getSelectedValuesList();
// your list of strings
List<String> listOfNameStrings = new ArrayList<String>(listOfPersonNames.size());
for(Object personName: listOfPersonNames) {
listOfNameStrings.add(personName.toString());
}
// your string from the resulting list
String listString = listOfNameStrings.toString();
System.out.println(listString);
//con.saveTeamListFile();
}
I am not entirely sure on the question so I am going to assume that you need to split that string into elements such as Lars,1,4,2,5. In which case you can split at the space
String[] names = nameString.split(" ");
You may though be better off separating the elements with another character in case in you want to use strings with spaces in future

Exporting specific pattern of string using split method in a most efficient way

I want to export pattern of bit stream in a String varilable. Assume our bit stream is something like bitStream="111000001010000100001111". I am looking for a Java code to save this bit stream in a specific array (assume bitArray) in a way that all continous "0"s or "1"s be saved in one array element. In this example output would be somethins like this:
bitArray[0]="111"
bitArray[1]="00000"
bitArray[2]="1"
bitArray[3]="0"
bitArray[4]="1"
bitArray[5]="0000"
bitArray[6]="1"
bitArray[7]="0000"
bitArray[8]="1111"
I want to using bitArray to calculate the number of bit which is stored in each continous stream. For example in this case the final output would be, "3,5,1,1,1,4,1,4,4". I figure it out that probably "split" method would solve this for me. But I dont know what splitting pattern would do that for me, if i Using bitStream.split("1+") it would split on contious "1" pattern, if i using bitStream.split("0+") it will do that base on continous"0" but how it could be based on both?
Mathew suggested this solution and it works:
var wholeString = "111000001010000100001111";
wholeString = wholeString.replace('10', '1,0');
wholeString = wholeString.replace('01', '0,1');
stringSplit = wholeString.split(',');
My question is "Is this solution the most efficient one?"
Try replacing any occurrence of "01" and "10" with "0,1" and "1,0" respectively. Then once you've injected the commas, split the string using the comma as the delimiting character.
String wholeString = "111000001010000100001111"
wholeString = wholeString.replace("10", "1,0");
wholeString = wholeString.replace("01", "0,1");
String stringSplit[] = wholeString.split(",");
You can do this with a simple regular expression. It matches 1s and 0s and will return each in the order they occur in the stream. How you store or manipulate the results is up to you. Here is some example code.
String testString = "111000001010000100001111";
Pattern pattern = Pattern.compile("1+|0+");
Matcher matcher = pattern.matcher(testString);
while (matcher.find())
{
System.out.print(matcher.group().length());
System.out.print(" ");
}
This will result in the following output:
3 5 1 1 1 4 1 4 4
One option for storing the results is to put them in an ArrayList<Integer>
Since the OP wanted most efficient, I did some tests to see how long each answer takes to iterate over a large stream 10000 times and came up with the following results. In each test the times were different but the order of fastest to slowest remained the same. I know tick performance testing has it's issues like not accounting for system load but I just wanted a quick test.
My answer completed in 1145 ms
Alessio's answer completed in 1202 ms
Matthew Lee Keith's answer completed in 2002 ms
Evgeniy Dorofeev's answer completed in 2556 ms
Hope this helps
I won't give you a code, but I'll guide you to a possible solution:
Construct an ArrayList<Integer>, iterate on the array of bits, as long as you have 1's, increment a counter and as soon as you have 0, add the counter to the ArrayList. After this procedure, you'll have an ArrayList that contain numbers, etc: [1,2,2,3,4] - Representing a serieses of 1's and 0's.
This will represent the sequences of 1's and 0's. Then you construct an array of the size of the ArrayList, and fill it accordingly.
The time complexity is O(n) because you need to iterate on the array only once.
This code works for any String and patterns, not only 1s and 0s. Iterate char by char, and if the current char is equal to the previous one, append the last char to the last element of the List, otherwise create a new element in the list.
public List<String> getArray(String input){
List<String> output = new ArrayList<String>();
if(input==null || input.length==0) return output;
int count = 0;
char [] inputA = input.toCharArray();
output.add(inputA[0]+"");
for(int i = 1; i <inputA.length;i++){
if(inputA[i]==inputA[i-1]){
String current = output.get(count)+inputA[i];
output.remove(count);
output.add(current);
}
else{
output.add(inputA[i]+"");
count++;
}
}
return output;
}
try this
String[] a = s.replaceAll("(.)(?!\\1)", "$1,").split(",");
I tried to implement #Maroun Maroun solution.
public static void main(String args[]){
long start = System.currentTimeMillis();
String bitStream ="0111000001010000100001111";
int length = bitStream.length();
char base = bitStream.charAt(0);
ArrayList<Integer> counts = new ArrayList<Integer>();
int count = -1;
char currChar = ' ';
for (int i=0;i<length;i++){
currChar = bitStream.charAt(i);
if (currChar == base){
count++;
}else {
base = currChar;
counts.add(count+1);
count = 0;
}
}
counts.add(count+1);
System.out.println("Time taken :" + (System.currentTimeMillis()-start ) +"ms");
System.out.println(counts.toString());
}
I believe it is more effecient way, as he said it is O(n) , you are iterating only once. Since the goal to get the count only not to store it as array. i woul recommen this. Even if we use Regular Expression ( internal it would have to iterate any way )
Result out put is
Time taken :0ms
[1, 3, 5, 1, 1, 1, 4, 1, 4, 4]
Try this one:
String[] parts = input.split("(?<=1)(?=0)|(?<=0)(?=1)");
See in action here: http://rubular.com/r/qyyfHNAo0T

To ge the part of the String and Compare witha a variable(String Variable)

I have the String like:
String value = "13,14,15,16,17"
But i Dont know how many numbers are there with comma separation.
I want to compare with the variable say:
String varValue = "16"
It may be in any postion..
I want to compare these two string variables....
Please can anyone help?
You can do this sort of thing:
String values = '13,14,15,16,17'
String required = '16'
values.tokenize( ',' ).with { toks ->
println "There are ${toks.size()} elements in the list"
println "The list contains $required is ${toks.contains( required )}"
println "It is at position ${toks.indexOf( required )}"
}
Which prints
There are 5 elements in the list
The list contains 16 is true
It is at position 3
Use the split method to put the numbers in an array and then compare.
Here: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
Do not quite understand your question.
Dont know how many numbers are there with comma separation
use String method split()
I want to compare with the variable say: String varValue = "16"
use String method contains()
You can use the split method to receive an Array. Turning the Array into a List will allow you to use some helper functions such as contains and indexOf, which can be used to return whether the token exists or the position of the token.
String value = "13,14,15,16,17";
//Checks existence
boolean contains = Arrays.asList(value.split(",")).contains("16");
//Returns position
int pos = Arrays.asList(value.split(",")).indexOf("16") + value.split(",").length + 1;
These examples all use Java.
If you are using Java , then following can be done to achieve this :
1. Split the input string into an array.
2. convert that array into a list .
Now
a) To find total elements separated by comma , Use :
size().
b) To find if the list contains required element or not , Use :
contains().
c) To find position of element in list , Use :
indexof()
So the code will look like :
import java.util.Arrays;
import java.util.List;
public class Test{
public static void main(String[] args) {
String inputString = "13,14,15,16,17";
String element = "16";
// Convert the string into array.
String values[] = inputString.split(",");
// Create a list using array elements.
List<String> valList = Arrays.asList(values);
System.out.println("Size :" + valList.size());
System.out.println("List contains 5 " + valList.contains(element));
System.out.println("Position of element" + valList.indexOf(element));
}
}

Print array without brackets and commas

I'm porting a Hangman game to Android and have met a few problems. The original Java program used the console, so now I have to somehow beautify the output so that it fits my Android layout.
How do I print an array without the brackets and commas? The array contains slashes and gets replaced one-by-one when the correct letter is guessed.
I am using the usual .toString() function of the ArrayList class and my output is formatted like: [ a, n, d, r, o, i, d ]. I want it to simply print out the array as a single String.
I fill the array using this bit of code:
List<String> publicArray = new ArrayList<>();
for (int i = 0; i < secretWordLength; i++) {
hiddenArray.add(secretWord.substring(i, i + 1));
publicArray.add("-");
}
And I print it like this:
TextView currentWordView = (TextView) findViewById(R.id.CurrentWord);
currentWordView.setText(publicArray.toString());
Replace the brackets and commas with empty space.
String formattedString = myArrayList.toString()
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "") //remove the left bracket
.trim(); //remove trailing spaces from partially initialized arrays
Basically, don't use ArrayList.toString() - build the string up for yourself. For example:
StringBuilder builder = new StringBuilder();
for (String value : publicArray) {
builder.append(value);
}
String text = builder.toString();
(Personally I wouldn't call the variable publicArray when it's not actually an array, by the way.)
For Android, you can use the join method from android.text.TextUtils class like:
TextUtils.join("",array);
first
StringUtils.join(array, "");
second
Arrays.asList(arr).toString().substring(1).replaceFirst("]", "").replace(", ", "")
EDIT
probably the best one: Arrays.toString(arr)
With Java 8 or newer, you can use String.join, which provides the same functionality:
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter
String[] array = new String[] { "a", "n", "d", "r", "o", "i", "d" };
String joined = String.join("", array); //returns "android"
With an array of a different type, one should convert it to a String array or to a char sequence Iterable:
int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };
//both of the following return "1234567"
String joinedNumbers = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).toArray(n -> new String[n]));
String joinedNumbers2 = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).collect(Collectors.toList()));
The first argument to String.join is the delimiter, and can be changed accordingly.
If you use Java8 or above, you can use with stream() with native.
publicArray.stream()
.map(Object::toString)
.collect(Collectors.joining(" "));
References
Use Java 8 Language Features
JavaDoc StringJoiner
Joining Objects into a String with Java 8 Stream API
the most simple solution for removing the brackets is,
convert the arraylist into string with .toString() method.
use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist).
the result string is your string with removed brackets.
I have used
Arrays.toString(array_name).replace("[","").replace("]","").replace(", ","");
as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.
I used join() function like:
i=new Array("Hi", "Hello", "Cheers", "Greetings");
i=i.join("");
Which Prints:
HiHelloCheersGreetings
See more: Javascript Join - Use Join to Make an Array into a String in Javascript
String[] students = {"John", "Kelly", "Leah"};
System.out.println(Arrays.toString(students).replace("[", "").replace("]", " "));
//output: John, Kelly, Leah
You can use the reduce method provided for streams for Java 8 and above.Note you would have to map to string first to allow for concatenation inside of reduce operator.
publicArray.stream().map(String::valueOf).reduce((a, b) -> a + " " + b).get();
I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution. I just made a loop to print Array list and used the list method " myList.get(index) " , it works like a charm.
Please refer to my Code & Output below:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList mylist = new ArrayList();
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 5; i++) {
System.out.println("Enter Value " + i + " to add: ");
mylist.add(scan.nextLine());
}
System.out.println("=======================");
for(int j = 0; j < 5; j++) {
System.out.print(mylist.get(j));
}
}
}
OUTPUT
Enter Value 0 to add:
1
Enter Value 1 to add:
2
Enter Value 2 to add:
3
Enter Value 3 to add:
4
Enter Value 4 to add:
5
=======================
12345
Just initialize a String object with your array
String s=new String(array);

Categories