Compare strings in array after split in Java - java

I have a string that I use split function on it in order to split it to the different parts.
Then I want to check if the array contain a certain value, I tried using a for loop and also converting the array to a List and using the contain options but I get the same result - the text is not in the array.
P.S.
I edited the code to show a better example.
String categories = "C1-C-D-A-1-В";
String[] cat = categories.split("-");
String catCode = "B";
//always return false
if (Arrays.asList(cat).contains(catCode))
{
//do somthing
}
for (int idxCat = 0; idxCat < cat.length; idxCat++) {
//always return false
if ((cat[idxCat]).equals(catCode))
{
//do somthing
break;
}
}

I made a quick demo of what it seems you are asking.
If you are trying to see if any of the strings in your array contain a certain value:
public class HelloWorld
{
public static void main(String[] args)
{
String[] strings = new String[] {"bob", "joe", "me"};
for (int i = 0; i < strings.length; i++)
{
if (strings[i].contains("bob"))//doing "b" will also find "bob"
{
System.out.println("Found it!");
}
}
}
}
The console output is: Found it!
I would suggest trying to use equalsIgnoreCase() as mentioned in the comments. You may also want to show the values in your array:
import java.util.Arrays;
public class HelloWorld
{
public static void main(String[] args)
{
String[] strings = new String[] {"bob", "joe", "me"};
System.out.println(Arrays.toString(strings));
for (int i = 0; i < strings.length; i++)
{
if (strings[i].contains("bob"))
{
System.out.println("Found it!");
}
}
}
}
Output:
[bob, joe, me]
Found it!
This can help you to figure out if the values in the strings in your array are actually the values that you think they are.

Related

JAVA GET API - 2D Array, Unable to retrieve?

I am getting a data varilable through an API like this (notice square brackets):
[
["2018-09-03",287.5,289.8,286.15,287.3,287.65,1649749.0,4750.35],
["2018-08-31",286.25,290.5,285.0,285.5,285.95,3716997.0,10691.41],
["2018-08-30",286.45,290.55,284.6,286.05,285.6,3861403.0, 11097.03]
]
What I am doing wrong in the below script? I am new to Java and need to print this block in table. Please help me, thanks in advance
public class ArrayLoopTest{
public static void main(String []args){
String[] data = new String[
["2018-09-03",287.5,289.8,286.15,287.3,287.65,1649749.0,4750.35],
["2018-08-31",286.25,290.5,285.0,285.5,285.95,3716997.0,10691.41],
["2018-08-30",286.45,290.55,284.6,286.05,285.6,3861403.0, 11097.03]
];
for (i=0;i < data.length;i++) {
System.out.println(data[i]);
}
}
}
Welcome to the wold of java.
Here are some things that you seem not to be doing well, as you know java is a strongly typed language. However from your code you are using a float in your array . perhaps you have declared that your array will contain strings only.
More so you are not declaring your array in a right way.
I will recommend that you work through this tutorial quickly Arrays in java.
But to resolve your issue you can do this instead
p
ublic static void main(String []args){
String[][] data = new String[][]{
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"},
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"},
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"},
};
for (int i=0;i < data.length;i++) {
for (int j = 0; j < data[i].lenght(); i++){
` System.out.print(data[i][j] + " ");
}
System.out.println("--------------")
}
}
While using an array keep in mind that array data structure can hold data of one type only. This essentially means that if a array is declared as String then it can have String type data only.
So, you can use the following code defining and printing the 2D array.
public static void main(String[] args) {
String[][] data = {
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"}
,{"2018-08-31","286.25","290.5","285.0","285.5","285.95","3716997.0","10691.41"}
,{"2018-08-30","286.45","290.55","284.6","286.05","285.6","3861403.0", "11097.03"}
};
for(int i=0;i<data.length;i++) {
for(int j=0;j<data[i].length;j++) {
System.out.print(data[i][j]);
}
System.out.println();
}
// or you can print like this
for(int i=0;i<data.length;i++) {
System.out.println(Arrays.toString(data[i])+",");
}
}
Edit:
You can use the com.google.gson library as shown below to get a 2D array:
//String apiResponse = get Api Response
JsonParser parser = new JsonParser(); // parser converstthe api response to Json
JsonObject obj = (JsonObject) parser.parse(apiResponse);
JsonObject obj1 = obj.getAsJsonObject("dataset");
JsonArray arr = obj1.get("data").getAsJsonArray();
String[][] newString = new String[arr.size()][arr.get(0).getAsJsonArray().size()];
for(int i=0;i<newString.length;i++) {
for(int j=0;j<newString[i].length;j++) {
newString[i][j] = arr.get(i).getAsJsonArray().get(j).getAsString();
}
}
System.out.println(Arrays.deepToString(newString));
It can be solved in two ways, one dimensional and two dimensional, if you are thinking to put different data types in a single array, that is not possible in java.You can put only one type of data type inside defined array type.
Two dimensional array code:
public class ArrayLoopTest{
public static void main(String []args){
String[][] data =
{
{"2018-09-03","287.5","289.8","286.15","287.3","287.65","1649749.0","4750.35"},
{ "2018-08-31","286.25","290.5","285.0","285.5","285.95","3716997.0","10691.41"},
{ "2018-08-30","286.45","290.55","284.6","286.05","285.6","3861403.0", "11097.03"}
};
for (int i=0;i < data.length;i++) {
{
for(int j=0;j<data[i].length;j++)
{
System.out.print(data[i][j]+" ");
}
System.out.println();
}
}
}}
One dimensional array code
public class ArrayLoopTest{
public static void main(String []args){
String[] data ={"2018-09-03,287.5,289.8,286.15,287.3,287.65,1649749.0,4750.35",
"2018-08-31,286.25,290.5,285.0,285.5,285.95,3716997.0,10691.41",
"2018-08-30,286.45,290.55,284.6,286.05,285.6,3861403.0, 11097.03"};
for (int i=0;i < data.length;i++)
{
System.out.println(data[i]);
}
}}
This won't compile as your array isn't of the correct format and the variable i is not defined. You need to loop over the items in each subarray and print them instead.
String[][] data = new String[][]{
{ "2018-09-03", "287.5", "289.8", "286.15", "287.3", "287.65", "1649749.0", "4750.35" },
{ "2018-08-31", "286.25", "290.5", "285.0", "285.5", "285.95", "3716997.0", "10691.41" },
{ "2018-08-30", "286.45", "290.55", "284.6", "286.05", "285.6", "3861403.0", "11097.03" }
};
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.print(data[i][j] + " ");
}
System.out.print("\n");
}

How to print an Array in reverse order (from end to beginning) separating with comma

The task is like in the title. I tried to wrote a code but something is going wrong and the output is bad. How to fix it?
import java.util.Collections;
import java.util.Arrays;
public class Hometask4ReverseArray {
public static void main(String[] args) {
String[] arrayNames = {"Sam", "Sara", "Tim", "Bob", "Kate"};
Arrays.sort(arrayNames, Collections.<String>reverseOrder());
for(int i = 0; i < arrayNames.length; i++) {
System.out.print(arrayNames[i]);
}
}
}
The output is:
TimSaraSamKateBob
It is working as expected. The reverseOrder() means alphabetically reverse.
If you need to print from the last to the first the solution is more simple, you don't need to sort:
public static void main(String[] args) {
String[] arrayNames = {"Sam", "Sara", "Tim", "Bob", "Kate"};
for(int i = arrayNames.length-1; i >= 0 ; i--) {
System.out.print(arrayNames[i] + (i != 0 ? + "," : ""));
}
}
As you can see I have used a contract if (or ternary operator) to add comma only if i counter's value is different from 0

How can i split up an ArrayList of strings between letters and numbers WITHOUT using the split method?

To take an arraylist of strings consisting of strings like:
fewf5677
kskfj654
pqoen444
mgnwo888
And i want to split them up BUT i DON'T want to use the split method because I have to perform other calculations with the letters that i'have split up.
SO i'have decided to use the subList method. But I can't seem to find a proper example of implementing this correctly. Take a look at my code. Below is a method that takes in an arraylist of strings as the parameter:
public static void splitup(ArrayList<String> mystrings){
mystrings.subList(String[] letters, double numbers);
}
So overall, how do I take each string of letters and numbers and store them into their own string arrays? For example, i want
fewf
kskfj
pqoen
mgnwo
to be in their own string along with
5677
654
444
888
to be their own numbers.
You could use regex as seen in this answer and then check for a pattern as shown in this answer as follows:
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringSplitter {
public static void main(String[] args) {
ArrayList<String> myStringsList = new ArrayList<String>();
ArrayList<String> stringsList = new ArrayList<String>();
ArrayList<String> numbersList = new ArrayList<String>();
myStringsList.add("fewf5677");
myStringsList.add("kskfj654");
myStringsList.add("pqoen444");
myStringsList.add("mgnwo888");
for (String s : myStringsList) {
String splittedString[] = s.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
for (String string : splittedString) {
Matcher match = Pattern.compile("[0-9]").matcher(string);
if (match.find()) {
numbersList.add(string);
} else {
stringsList.add(string);
}
}
}
for (String s : numbersList) {
System.out.println(s);
}
for (String s : stringsList) {
System.out.println(s);
}
}
}
This will output:
5677
654
444
888
fewf
kskfj
pqoen
mgnwo
Remember that split() takes a regex as parameter, not a String and so, you can do something like the above code to get the desired output.
What you are trying to do is a bit strange. Why are you trying to overload subList method?
One of possible examples of what you could do is to iterate over mystrings list and separate each string into two variables.
http://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/
If you are familiar with regular expressions you can use them them.
If not you can iterate over string characters to separate letters from number.
http://java11s.blogspot.com/2012/02/java-program-to-separate-alphabets-and.html
Then add result to two separate lists List<String> and List<Double> (or probably List<Integers>) or create custom data structure.
You can try this way :
If we consider that the format of your input is a String in which you want to extract integers, then you should to test one element by one:
Main
public static void main(String[] a) {
List<String> myList = new ArrayList<>();
myList.add("fewf5677");
myList.add("kskfj654");
myList.add("pqoen444");
myList.add("mgnwo888");
List<String> listStrings = new ArrayList<>();
List<Integer> listIntegers = new ArrayList<>();
for (int i = 0; i < myList.size(); i++) {
listStrings.add(getStringPart(myList.get(i)));
listIntegers.add(Integer.parseInt(getIntegerPart(myList.get(i))));
}
System.out.println(listStrings);
System.out.println(listIntegers);
}
Get the string part of your element
private static String getStringPart(String str) {
String s = "";
for (int i = 0; i < str.length(); i++) {
if (!testInteger(str.charAt(i))) {
s += str.charAt(i);
} else {
break;
}
}
return s;
}
Get the Integer part of your element
private static String getIntegerPart(String str) {
String s = "";
for (int i = 0; i < str.length(); i++) {
if (testInteger(str.charAt(i))) {
s += str.charAt(i);
}
}
return s;
}
A method to check if your str is and Integer or not
private static boolean testInteger(char str) {
try {
Integer.parseInt(str+"");
return true;
} catch (Exception e) {
return false;
}
}
Output
[fewf, kskfj, pqoen, mgnwo]
[5677, 654, 444, 888]
Hope this can help you.

Finding the indexes of multiple words in a string

I swear I did this a while back and it worked. But I can't remember how I did it. I want to find the indexes of multiple words in a string. The code below only works for one word. I need a more eloquent solution for dealing with several.
import java.util.*;
public class test {
public static List<List<Boolean>> work;
public static void main (String[] args) {
String test = "I'm trying to both extract and replaces. This that and the other";
String word = "I'm";
for (int i = -1; (i = test.indexOf(word, i + 1)) != -1; ) {
System.out.println(i);
}
}
}
Let's say I wanted to find the index of “both” and “other.”
I did some more research, this appears to be what you are asking for:
String test = "I'm trying to both extract and replaces. This that and the other";
String[] words = test.split("\\s+");
for (int i = 0; i < words.length; i++) {
words[i] = words[i].replaceAll("[^\\w]", "");
}
System.out.println(Arrays.asList(words).indexOf("both"));
Result:
3
Keep in mind that Java counts including 0, so "both" is actually at index 4 for us humans.
----Old Solution----
The question is vague about what they want, but this will return the index number corresponding to each word via HashMap:
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
String test = "I'm trying to both extract and replaces. This that and the other";
String[] words = test.split("\\s+");
for (int i = 0; i < words.length; i++) {
words[i] = words[i].replaceAll("[^\\w]", "");
}
for(int i = 0; i < words.length; i++){
hmap.put(i, words[i]);
}
System.out.println(hmap);
Result:
{0=Im, 1=trying, 2=to, 3=both, 4=extract, 5=and, 6=replaces, 7=This, 8=that, 9=and, 10=the, 11=other}
public static void main (String[] args)
{
String test="I'm trying to both extract and replaces. This that and the other";
String[] words={"other","This","that"};
for(int j=0;j<words.length;j++)
{
for(int i=-1;(i=test.indexOf(words[j],i+1))!=-1;)
{
System.out.println(words[j]+" "+ i);
}
}
}
ouput
other 59
This 41
that 46
buddy ... I was trying to point you in the right direction ... not give you complete working code :) Here is a complete working code:
public static void main (String[] args)
{
String test = "I'm trying to both extract and replaces. This that and the other";
String[] words = {"I'm", "other", "both"};
for (int j=0; j < words.length; j++)
{
System.out.println("Word: " + words[j] + " is at index: " + test.indexOf(words[j]));
}
}
This way, you will not get ArrayIndexOutOFBounds exception. You are going through each word once.
But for each word, you have go through entire test string once. In your earlier code, you were using i = test.indexOf(word) in the loop. If the words were not in the order of appearing in test string, this will create problem.
For eg: test = "I'm a rockstar"
words = {"rockstar", "a"}
In this case, the loop variable i moves forward to index where 'rockstar' is found but then will not find 'a' after that as test string doesn't contain an 'a' after 'rockstar'.
But in the current code I posted, order of words can be anything.
Hope its clear.
I believe you're referencing the answer from this SO question. To use it for more than one word, all you need is a simple data structure to store the words you want to find, loop over that, and return a map holding the word and its corresponding locations, as follows:
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class WordFinder {
public static void main(String[] args) {
String phrase = "0123hello9012hello8901hello7890";
String[] words = { "hello", "90" };
Map<String, Stack<Integer>> dest = findWordsInString(words, phrase);
System.out.println(dest.toString());
}
public static Map<String, Stack<Integer>> findWordsInString(String[] words, String phrase) {
Map<String, Stack<Integer>> dest = new HashMap<>();
for (String word : words) {
Stack<Integer> locations = new Stack<>();
for (int loc = -1; (loc = phrase.indexOf(word, loc + 1)) != -1;) {
locations.add(loc);
}
dest.put(word, locations);
}
return dest;
}
}
Program Output:
{90=[9, 19, 29], hello=[4, 13, 22]}

replacing elements of an array change by change

I'm trying to do some basics concerning an array of elements, specifically characters. My question is, how do I get the program to print my changes one by one? for example (I do not want my output going from "moon" to "mOOn" in one instance, but from "moon" to "mOon" to "mOOn", like that. Here is my code.
import java.util.*;
public class Practice
{
public static void main(String[] args)
{
String array[] = {"uuuuuuuupppppppssssssssss"};
System.out.println(Arrays.toString(array));
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i] = array[i].replace('p', 'P'));
//trying to print each change here
}
}
}
Thanks again!
EDIT/Update: I got the output to get the loop right, but the output is still not what I want (basically output: uPPPPPPS, uPPPPPPs, uPPPPPs, etc until the length of p ends). Any hints on what I could do? Thanks!
public static void main(String[] args){
String array = "uuuuuuuupppppppssssssssss";
System.out.println(array);
char[] chars = array.toCharArray(): //converted
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 'p') {
System.out.println(array.replace('p', 'P'));
}
}
}
public static void main(String[] args)
{
String array = "uuuuuuuupppppppssssssssss";
System.out.println(array);
while ( array.contains("p") )
{
array = array.replaceFirst("p", "P");
System.out.println(array);
}
}

Categories