String arr[]={"",""};
if(arr!=null && arr.length >0){
// the condition is becoming true
}
I need to check for empty values and return false
An empty string is still a value. The array has 2 'slots' available, therefore, its length is '2'.
You can query the individual objects in these slots, for example with: for (String elem : arr) { if (elem.isEmpty()) ..... ; }
You can stream the array, filter out elements that are not empty strings and get the count. Like,
boolean b = Arrays.stream(arr).filter(x -> !x.isEmpty()).count() != 0;
That will be false if the array is "empty" (and true otherwise).
String arr[] = ["", ""];
if(arr!=null && Array.length>0){
for (int i = 0; i < arr.length; i++) {
if(arr[i]==""){
return false;
break;
}
}
}
String arr[]={"",""};
int flag = 0;
for (int i=0; i<arr.length; i++){
if(arr[i]!="") {
flag = 1;
break;
}
}
if(flag==0){
//your code
}
Related
I have a .txt file which has data for states as given below:
AL,Alab,4860
AK,Alas,7415
AZ,Ariz,6908
AR,Arka,2988
I have made a function which counts how many states there are that start with the initial passed as such:
public int CInitial(char initial) {
int total = 0;
for(int i = 0; i < states.length; i++) { //states is an array which includes all states present in the .txt file
String testString = states[i].getName(); // getName gets the name of the states present in the .txt file
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
total++;
}
}
}
return total;
}
This would return the number 4 if "A" is passed and 0 if any other initial is passed as there are 4 states that begin with the letter "A".
Now how can I create a new function that passes a character and returns the name of all the states that begin with that character? For Instance this is the initial return type needed for this, however I'm having troubles starting this. Is the process identical to the countStatesCountByInitial function I created?
public State[] CByInitial(char initial) {
return new State[] {}; //to be completed
}
Yes, it will be very similar to the countStatesCountByInitial. The main difference is each time you find a match, you want to add the state into the array. Since we don't know the size of the array beforehand, we may want to use a List instead.
public State[] getStatesCountByInitial(char initial) {
ArrayList<State> found = new ArrayList<>();
// this is the same as before
for(int i = 0; i < states.length; i++) {
String testString = states[i].getName();
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
// except here when you find a match, you add it into the list
found.add(states[i]);
}
}
}
// return as array
return found.toArray(new State[found.size()]);
}
As suggested by Patrick, we can avoid using List by using countStatesCountByInitial to initialize the size of the states.
public State[] getStatesCountByInitial(char initial) {
int matchSize = countStatesCountByInitial(initial);
States[] found = new States[matchSize];
int foundIndex = 0;
// this is the same as before
for(int i = 0; i < states.length; i++) {
String testString = states[i].getName();
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
// except here when you find a match, you add it into the array
found[foundIndex] = states[i];
foundIndex++;
}
}
}
// return the array
return found;
}
You can done both operations simply by one method.
public static ArrayList<State> getStatesCountByInitial(char initial) {
ArrayList selectedStates = new ArrayList<State>();
for(int i = 0; i < states.length; i++) {
if(states.charAt(0) == initial){
selectedStates.add(states[i]);
}
}
return selectedStates;
}
This method will return a arraylist.
If you want to get the count, call this method and get the size of the array.
ArrayList<State> statesNew = getStatesCountByInitial('A');
int count = statesNew.size();
I have a string hackkkerrank and i have to find if any subsequence gives a result as hackerrank, if it is present then it gives result as YES otherwise NO.
Sample:
hereiamstackerrank: YES
hackerworld: NO
I don't know which String method should be applied, can anyone help me how to do it?
Here is my code:
static String hackerrankInString(String s) {
char str[] = {
'h','a','c','k','e','r','a','n','k'
};
while (s.length() >= 10) {
for (int i = 0; i < s.length(); i++) {
for (char c: str) {
if (s.indexOf(c)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
}
Here is a built-in way, using regex:
String regex = "[^h]*+h[^a]*+a[^c]*+c[^k]*+k[^e]*+e[^r]*+r[^r]*+r[^a]*+a[^n]*+n[^k]*+k.*";
System.out.println("hereiamstackerrank".matches(regex) ? "YES" : "NO");
System.out.println("hackerworld".matches(regex) ? "YES" : "NO");
Output
YES
NO
You can make a generic method to check for subsequence like this:
public static boolean containsSubsequence(String subsequence, String text) {
StringBuilder buf = new StringBuilder();
for (int i = 0, j; i < subsequence.length(); i = j) {
j = subsequence.offsetByCodePoints(i, 1);
String ch = Pattern.quote(subsequence.substring(i, j));
buf.append("[^").append(ch).append("]*+").append(ch);
}
String regex = buf.append(".*").toString();
return text.matches(regex);
}
Test
System.out.println(containsSubsequence("hackerrank", "hereiamstackerrank") ? "YES" : "NO");
System.out.println(containsSubsequence("hackerrank", "hackerworld") ? "YES" : "NO");
Output
YES
NO
Of course, it is not very efficient, but it is one way to do it.
For a simpler and more efficient solution, that doesn't handle characters in the SupplementÂary Planes, you'd do this:
public static boolean containsSubsequence(String subsequence, String text) {
int j = 0;
for (int i = 0; i < text.length() && j < subsequence.length(); i++)
if (text.charAt(i) == subsequence.charAt(j))
j++;
return (j == subsequence.length());
}
Here is an old fashioned looping way, which increments the starting position of the second string based upon where the last char was found
String str1 = "hackerrank";
String str2 = "hereiamstackerrank";
int index = 0;
for (int i = 0; i < str1.length(); i++)
{
boolean notfound = true;
int x = index;
for (; x < str2.length(); x++) {
if (str1.charAt(i) == str2.charAt(x)) {
notfound = false;
break;
}
}
if (notfound) {
System.out.println("NO");
return;
}
index = x + 1;
}
System.out.println("YES");
An in-efficient alternative is
for (int i = 0; str1.length() > 0 && i < str2.length(); i++)
{
if (str1.charAt(0) == str2.charAt(i)) {
str1 = str1.substring(1);
}
}
System.out.println(str1.length() == 0 ? "YES" : "NO");
static String re="";
static String hackerrankInString(String s) {
String pattern="[^h]*+h[^a]*+a[^c]*+c[^k]*+k[^e]*+e[^r]*+r[^r]*+r[^a]*+a[^n]*+n[^k]*+k.*";
if(s.matches(pattern)){
re="YES";
}else{
re="NO";
}
return re;
}
There's no built in function in core libraries to check subsequence. There's one for substring but none for subsequence you're looking for.
You'll have to code it yourself.
Below is the pseudo code for this:
1. Traverse both original string and string under test.
2. Increment both's counter if characters are equal
3. Else increment originalString's counter only.
4. Repeat 2-3 `while` both strings are `not` empty.
5. Given string under test is subsequence if its counter is exhausted.
I'm trying to create a simple indexOf() method that returns an int value and that recognizes a string (not char) of an string array.
public int indexOf(String str) {
/*Getting and return the index of the first
*occurrence of the specified String. Return
*-1 if string not in the list
*/
for(int i = 0; i < listArray.length; i++) {
if(listArray[i].equals(str)) {
return str.indexOf(listArray[i]);
}
}
return -1;
}
I'm using indexOf() method from Java for the first return, but it always returns 0. Why is this, and is there a better way to write this method?
Your for-loop is fine, the problem there is that when you find it, you are returning the index where the string is in itself, and that will always be 0.
For instance, "hello" is in the position 0 for the string "hello".
You should just return i, like this:
public int indexOf(String str) {
/* Getting and return the index of the first
* occurrence of the specified String. Return
* -1 if string not in the list
*/
for (int i = 0; i < listArray.length; i++) {
if (listArray[i].equals(str)) {
// If we get here, it means that the item for position `i` is equal to `str`.
return i; // just return `i`
}
}
return -1;
}
return i; by definition listArray[i] is equal to str.
Because, whenever you run return str.indexoOf(listArray[i]);, you already have str equals listArray[i]. Of course you are getting 0 all the time, it's equivalent to str.indexOf(str);
And you really don't need to do that. You have already found an element in the list that equals the given string, just return its location:
return i;
You must return i (index) when the if condition is satisfied.
public int indexOf(String str) {
for(int i = 0; i < listArray.length; i++) {
if(listArray[i].equals(str)) {
return i;
}
}
return -1;
}
I think you have got confused. if you want to find a string from ArrayList and if you have already found the string in your if(listArray[i].equals(str)) then all you have to do is just return that index i as you have already found it.
for(int i=0;i<listArray.length;i++){
if(listArray[i].equals(str)){
return i;
}
}
is the answer.
Always remember: If you even post the contents or sample of your listArray and sample string to find in it... It will help us better to understand where exactly you are stuck
You can do this using a for loop.
Check if the string matches using equals.
If yes, return the index.
If you come out of the for loop, return -1.
public int indexOf(String iparam){
String astring = "" //YOUR OWN STRING
boolean astat = false;
List<Integer> alist = null;
for(int i=0; i<astring.toCharArray().length; i++){
alist = new ArrayList<>();
for(int j=0; j<iparam.toCharArray().length; j++){
try{
if(astring.toCharArray()[i+j] == iparam.toCharArray()[j]){
alist.add(i+j);
}else{
break;
}
}catch(Exception ex){
ex.printStackTrace();
break;
}
}
if(alist.size() == iparam.toCharArray().length){
astat = true;
break;
}
}
if(astat){
return alist.get(0);
}else{
return -1;
}
}
I was trying to remove the duplicates from the list of arrays, I was trying to use simple for loop instead of hashset..
Can anyone suggest how can I improve my program:
public class removeduplicates {
public static void main(String[] args) {
String[] words={"Others","Others","Others","Sentence"};
String output=words[0];
int count=0;
for(int i=0;i<words.length-1;i++) {
for(int j=i+1;j<words.length;j++) {
if(words[i].equals(words[j])) {
count++;
}
else {
output=output+words[j];
}
}
i=count;
}
System.out.println(output);
}
}
In this program if we give input as Others, Sentence, Others, Sentence then I am not getting the required output: I need just Others and Sentence as output...
If possible I have a condition that when I am entering words array, I need the output array with only unique values in the same array words.
String [] input={"other", "other","sentence","other"};
String current=input[0];
boolean found=false;
for(int i=0; i<input.length; i++){
if (current == input[i] && !found) {
found = true;
} else if (current != input[i]) {
System.out.print(" " + current);
current = input[i];
found = false;
}
}
I suggest to use collections as you can't resize an array
ArrayList<String> noDuplicateList = new ArrayList<>();
String[] words={"Others","Others","Others","Sentence"};
for(int i=0;i<words.length;i++) {
if(!noDuplicateList.contains(words[i])){
noDuplicateList.add(words[i]);
}
}
Here's a link
The simplest way to solve the duplication is declared already using HashSet, Anyway look at this code using loop:
Step 1: replace duplicate value with null
String[] words={"Others","B","Sentence","A","Others","A","Sentence"};
for(int i=0; i < words.length ;i++) {
String toBeRemoved = words[i];
for(int j=i+1 ; j < words.length; j++) {
if(words[j] != null && words[j].equals(toBeRemoved)) {
words[i] = null;
}
}
}
Now if you print the words values then the output will be:
System.out.println(Arrays.asList(words));
output: [null, B, null, null, Others, A, Sentence]
Step 2: Remove the null values (there are many ways to do it) for example:
List<String> list = new ArrayList<>(Arrays.asList(words));
list.removeIf(new Predicate<String>() {
#Override
public boolean test(String t) {
return (t == null || t.length() < 0);
}
});
words = list.toArray(new String[0]);
Using lambda JDK 8:
words = Arrays.stream(words).filter(t -> (t != null && t.length() > 0)).toArray(String[]::new);
Now if you print the words values then the output will be:
System.out.println(Arrays.asList(words));
output: [B, Others, A, Sentence]
I have two String Lists just like below:
List1 (Generated by sql resultset)
10001
10100
10001
List2 (Generated by sql resultset)
10000
10000
10000
Button Action;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
createList1();
createList2();
difference();
} catch (Exception ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
difference void;
public void difference (){
int minLen = Math.min(List1.get(0).length(), List2.get(0).length());
for (int i = -1 ; i != minLen ; i++) {
char chA = List1.get(0).charAt(i);
char chB = List2.get(0).charAt(i);
if (chA != chB) {
System.out.println(chA);
}
}
}
I want to find which index numbers are different in List1 for index 0.
Thanks in advance.
Make a loop that iterates the index i from zero the length of the shorter of the two strings, and compare characters one by one, using the == operator:
int minLen = Math.min(a.length(), b.length());
for (int i = 0 ; i != minLen ; i++) {
char chA = a.charAt(i);
char chB = b.charAt(i);
if (chA != chB) {
...
}
}
Before starting the comparison you need to check that a and b are not null. Otherwise, getting the length is going to trigger a null reference exception.
Try this:
public List<Integer> findDiffIndexes(String s1, String s2 ) {
List<Integer> indexes = new ArrayList<Integer>();
for( int i = 0; i < s1.length() && i < s2.length(); i++ ) {
if( s1.charAt(i) != s2.charAt(i) ) {
indexes.add( i );
}
}
return indexes;
}
https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringUtils.html#difference%28java.lang.String,%20java.lang.String%29
public static String difference(String str1,
String str2)
Compares two Strings, and returns the portion where they differ. (More precisely, return the remainder of the second String, starting
from where it's different from the first.)
For example, difference("i am a machine", "i am a robot") -> "robot".
StringUtils.difference(null, null) = null
StringUtils.difference("", "") = ""
StringUtils.difference("", "abc") = "abc"
StringUtils.difference("abc", "") = ""
StringUtils.difference("abc", "abc") = ""
StringUtils.difference("ab", "abxyz") = "xyz"
StringUtils.difference("abcde", "abxyz") = "xyz"
StringUtils.difference("abcde", "xyz") = "xyz"
Parameters:
str1 - the first String, may be null
str2 - the second String, may be null
Returns:
the portion of str2 where it differs from str1; returns the empty String if they are equal
Since:
2.0
Do loop on List 1 and List2, and compare index value like,
I assume you that both list has same size so,
for(int i=0;i<list1.size();i++)
{
if(!list1.get(i).equals(list2.get(i))
{
System.out.println("Not equal value of Index="+i);
}
}
Assuming the two Strings will always be the same length...
String first = "10000";
String second = "10101";
ArrayList differentIndexes = new ArrayList();
for(int i=0; i<first.length(); i++){
if(first.charAt(i)!=second.charAt(i)){
differentIndexes.add(i);
}
}