Identify the Element in String array in java - java

I want to identify the elements in letters and elements in numbers in String array.Is there any other way to do it?
String a[]={"aaaa","111111","bbbbbb"};
for(int i=0;i<a.length;i++)
{
post your code for this FOR LOOP
}

They say that you have a problem... so you choose regular expressions to solve it, now you have two problems. :-)
However, if speed is not that much of an issue, you could attempt it, assuming you have good unit tests in place. Something along the lines of:
public static void testRegularExpressionForElement() {
String[] a = new String[] {"test1", "13", "blah", "1234.44"};
Pattern pattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+");
for (String element : a) {
if (pattern.matcher(element).matches()) {
System.out.println(element + " is a number");
} else {
System.out.println(element + " is not a number");
}
}
}
What's nice about the above, is that you can adapt the expression to match exactly what you want.
Another approach would be is to use Integer.parseInt() and catching the exceptions, but this is bad programming as you're using exceptions for logic.

Traverse the array and write a function to check isNumeric or not.
for (a1 : a){
boolean isNumbr= isNumeric(a1);
}
...
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}

Related

How to check if the String object passed to the method contains at least one of the words from the list- JAVA [duplicate]

This question already has answers here:
How to check whether a List<String> contains a specific string?
(4 answers)
Closed last year.
I need help with creating a method that takes an object of the String type in the input arguments and a list of objects of the String type. The list contains forbidden words. How can I check if the String object passed to the method contains at least one of the words from the list?
public class Filter {
public static void main(String[] args) {
wordsFilter("This sentence contains a forbidden word");
}
private static void wordsFilter(String sentence) {
List<String> forbiddenWords = new ArrayList<>();
forbiddenWords.add("forbiddenWord");
forbiddenWords.add("forbidden word");
for (String word : forbiddenWords) {
if (sentence.contains(word)) {
System.out.println("The content cannot be displayed");
} else {
System.out.println(sentence);
}
}
}
}
Looks like you are missing a condition to exit the loop when a forbidden word was found:
private static void wordsFilter(String sentence) {
List<String> forbiddenWords = new ArrayList<>();
forbiddenWords.add("forbiddenWord");
forbiddenWords.add("forbidden word");
boolean doesContainAnyForbiddenWords = false;
for (String word : forbiddenWords) {
if (sentence.contains(word)) {
doesContainAnyForbiddenWords = true;
break; // leave the loop
} else {
System.out.println(sentence);
}
}
if (doesContainAnyForbiddenWords) {
System.out.println("The content cannot be displayed");
} else {
System.out.println(sentence);
}
}
You can do this easily using the Streams API
Optional<String> potential_forbidden_word =
forbiddenWords.stream().filter(word -> sentence.contains(word)).findFirst();
if(potential_forbidden_word.isPresent())
System.out.println("don't usw: "+potential_forbidden_word.get());
else
System.out.println("the sentence is clean");
you can even shorten the stream:
Optional<String> potential_forbidden_word =
forbiddenWords.stream().filter(sentence::contains).findFirst();
AS #Adriaan Koster mentioned: you can simply use the terminal operation anyMatch(Predicate):
boolean contains_forbidden_word =
forbiddenWords.stream().anyMatch(sentence::contains);
you might check for with equalsIgnoreCase() because "foo" or "Foo" or "FoO" and so on might also be forbidden.

Java - search a string in string array [duplicate]

This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 6 years ago.
In java do we have any method to find that a particular string is part of string array.
I can do in a loop which I would like to avoid.
e.g.
String [] array = {"AA","BB","CC" };
string x = "BB"
I would like a
if (some condition to tell whether x is part of array) {
do something
} else {
do something else
}
Do something like:
Arrays.asList(array).contains(x);
since that return true if the String x is present in the array (now converted into a list...)
Example:
if(Arrays.asList(myArray).contains(x)){
// is present ... :)
}
since Java8 there is a way using streams to find that:
boolean found = Arrays.stream(myArray).anyMatch(x::equals);
if(found){
// is present ... :)
}
You could also use the commons-lang library from Apache which provides the much appreciated method contains.
import org.apache.commons.lang.ArrayUtils;
public class CommonsLangContainsDemo {
public static void execute(String[] strings, String searchString) {
if (ArrayUtils.contains(strings, searchString)) {
System.out.println("contains.");
} else {
System.out.println("does not contain.");
}
}
public static void main(String[] args) {
execute(new String[] { "AA","BB","CC" }, "BB");
}
}
This code will work for you:
bool count = false;
for(int i = 0; i < array.length; i++)
{
if(array[i].equals(x))
{
count = true;
break;
}
}
if(count)
{
//do some other thing
}
else
{
//do some other thing
}

i want to get the character that a string is made of. for example if i have str=aabbc then the answer is abc

Here is the function i wrote. it take a Stringbuffer text then assign v[0]=text[0] , then starts from text[1] >>>text[n-1] the comparing. The vector v should contain the characters. I don't know where is the problem. Can you help me?
public void setdirectory(StringBuffer text)
{
String temp;
boolean t;
v.add(0,String.valueOf(text.charAt(0))); //A[0]=first letter in text.
for(int i=1;i<text.length();++i)
{
temp=String.valueOf(text.charAt(i));
try{
for(int j=0;j<v.capacity();++j)
{
if(!temp.equals(v.elementAt(j)))
{
v.add(i,temp);
}
v.trimToSize();
}
// System.out.println(v.capacity());
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("usage error");
}
}
}
If you're using Java 8+, then it might be simpler to use the new Stream API...
String str = "aabbc";
StringBuilder sb = new StringBuilder(str.length());
str.chars().distinct().forEach(c -> sb.append((char)c));
System.out.println(sb.toString());
Which prints
abc
I'd write a function to get unique characters, and assuming you need to preserve the insertion order, I'd use a LinkedHashSet<Character> and I'd prefer StringBuilder over StringBuffer. Something like
static String getUniqueCharacters(String text) {
Set<Character> set = new LinkedHashSet<>();
for (char ch : text.toCharArray()) {
set.add(ch);
}
StringBuilder sb = new StringBuilder();
for (char ch : set) {
sb.append(ch);
}
return sb.toString();
}
An alternative Java 8 solution is:
String str = "aabbc";
String str2 = str.chars().distinct().mapToObj(j->""+(char)j).collect(Collectors.joining());
System.out.println(str2);
Behind the scenes, this is similar to other answers here as IntStream::distinct is implemented using a LinkedHashSet<Integer>, and joining uses a StringBuilder.
You need to keep track of where you are adding your value in the vector. Also the number of objects in a vector is size(), not capacity() (look up the API for both; capacity() shows the current number of 'spaces' filled and available to fill before the vector needs to expand, it doesn't show how much of it has actually been filled).
Doh, and the third reason your code would not have worked: you were adding the character every time it found a non-matching one in the vector (over-writing itself each time so you would have only seen the last addition)
public void setdirectory(StringBuffer text) {
String temp;
boolean t;
int addAt = 0;
v.add(addAt,String.valueOf(text.charAt(0))); //A[0]=first letter in text.
for(int i=1;i<text.length();++i) {
temp=String.valueOf(text.charAt(i));
try {
boolean found = false
for(int j=0;j<v.size();++j) {
if(temp.equals(v.elementAt(j))) {
found = true;
break;
}
}
if (!found) {
addAt++;
v.add(addAt,temp);
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("usage error");
}
}
}
And although this would fix your code as it stands (which will be an important exercise for a beginner programmer), there are other ways of doing this that you should explore.

Find word in random string

Say I have a string that may look like:
"RAHDTWUOPO"
I know the word I'm looking for, for example:
"WORD"
what would be the best method for finding if I can make up "WORD" with a string like "RAHDTWUOPO"
EDIT:
Because of this question being unclear Id thought Id put more detail. What I wanted to achieve was to find if a word I knew beforehand could be made up from a random string of letters. Wasn't sure how to go about this, with a loop or if there was some other method.
I had come up with something quickly in my head but I knew it was to much effort, but I'll put it here to make this question more clearer of what I wanted to achieve.
public class MyLetterObject {
private String letter;
private Boolean used;
public String getText() {
return letter;
}
public void setLetter(String letter) {
this.letter = letter;
}
public Boolean getUsed() {
return used;
}
public void setUsed(Boolean used) {
this.used = used;
}
}
boolean ContainsWord(String Word, String RandomLetterString) {
List<MyLetterObject> MyLetterList = new ArrayList<MyLetterObject>();
for (char ch : RandomLetterString.toCharArray()) {
MyLetterObject mlo = new MyLetterObject();
mlo.setLetter(String.valueOf(ch));
mlo.setUsed(false);
MyLetterList.add(mlo);
}
String sMatch = "";
for (char Wordch : Word.toCharArray()) {
for (MyLetterObject o : MyLetterList) {
if (o.getUsed() == false
&& String.valueOf(Wordch).equals(o.getText())) {
o.setUsed(true);
sMatch = sMatch + String.valueOf(Wordch);
break;
}
}
}
if (sMatch.equals(Word)) {
return true;
} else {
return false;
}
}
As you can see to much effort. Evgeniy Dorofeev answer is much more better for the purpose of just finding if a word can be made from a string made up of letters in a random order.
try
boolean containsWord(String s, String w) {
List<Character> list = new LinkedList<Character>();
for (char c : s.toCharArray()) {
list.add(c);
}
for (Character c : w.toCharArray()) {
if (!list.remove(c)) {
return false;
}
}
return true;
}
You search every letter, one by one in the first String.
String randomString = "RAHDTWUOPO";
String word = "WORD";
for(int i=0;i<word.length; i++){
if(randomString.contains(word.charAt(i))){
// Yey, another letter found
}
}
Then you only have to test if for every i the letter was actually found, if not, the word is not included in the randomString.
You need find, that all letters from your word "WORD" exists in input string at list once.
Simple loop will do it for you but performance will not be best one.
You can use guava library multiset:
http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained
Multiset wordsMultiset = HashMultiset.create();wordsMultiset.addAll(words);// now we can use wordsMultiset.count(String) to find the count of a word
This example is about words, adopte it to chars of your input string.

How to check Type before casting in java

I am casting my String variables to integer and double. I want to check whether the String variable contains valid Integer or Double value at runtime.
I us following code but it not works for me.
String var1="5.5";
String var2="6";
Object o1=var1;
Object o2=var2;
if (o1 instanceof Integer)
{
qt += Integer.parseInt( var1);// Qty
}
if (o2 instanceof Double)
{
wt += Double.parseDouble(var2);// Wt
}
Try to parse the int and catch the exception if it fails:
String var1="5.5";
try {
qt += Integer.parseInt( var1);
}
catch (NumberFormatException nfe) {
// wasn't an int
}
You can use patterns to detect if a string is an integer or not :
Pattern pattern = Pattern.compile("^[-+]?\\d+(\\.\\d+)?$");
Matcher matcher = pattern.matcher(var1);
if (matcher.find()){
// Your string is a number
} else {
// Your string is not a number
}
You will have to find the correct pattern (I haven't used them for awhile) or someone could edit my answer with the correct pattern.
*EDIT** : Found a pattern for you. edited the code. I did not test it but it is taken from java2s site which also offer an even more elgant approach (copied from the site) :
public static boolean isNumeric(String string) {
return string.matches("^[-+]?\\d+(\\.\\d+)?$");
}
First of all, your if condition will certainly fail, because the object reference actually points to a String object. So, they are not instances of any integer or double.
To check whether a string can be converted to integer or double, you can either follow the approach in #Bedwyr's answer, or if you don't want to use try-catch, as I assume from your comments there (Actually, I don't understand why you don't want to use them), you can use a little bit of pattern matching: -
String str = "6.6";
String str2 = "6";
// If only digits are there, then it is integer
if (str2.matches("[+-]?\\d+")) {
int val = Integer.parseInt(str2);
qt += val;
}
// digits followed by a `.` followed by digits
if (str.matches("[+-]?\\d+\\.\\d+")) {
double val = Double.parseDouble(str);
wt += val;
}
But, understand that, Integer.parseInt and Double.parseDouble is the right way to do this. This is just an alternate approach.
Maybe regexps could suit your needs:
public static boolean isInteger(String s) {
return s.matches("[-+]?[0-9]+");
}
public static boolean isDouble(String s) {
return s.matches("[-+]?([0-9]+\\.([0-9]+)?|\\.[0-9]+)");
}
public static void main(String[] args) throws Exception {
String s1 = "5.5";
String s2 = "6";
System.out.println(isInteger(s1));
System.out.println(isDouble(s1));
System.out.println(isInteger(s2));
System.out.println(isDouble(s2));
}
Prints:
false
true
true
false
Integer.parseInt and Double.parseDouble return the integer/double value of the String. If the String is not a valid number, the method will thrown a NumberFormatException.
String var1 = "5.5";
try {
int number = Integer.parseInt(var1); // Will fail, var1 has wrong format
qt += number;
} catch (NumberFormatException e) {
// Do your thing if the check fails
}
try {
double number = Double.parseDouble(var1); // Will succeed
wt += number;
} catch (NumberFormatException e) {
// Do your thing if the check fails
}

Categories