How to make spaced text .equal() to unspaced text - java

I am working on code that takes two inputs like the following:
,Air Condition,
, Air Condition,
This text is received from a JSON object and the commas are something that must be considered.
As can be seen, one has white space at the beginning and the other doesn't. How can I compare them using the equals()?
So far, I have used the following code to compare the two strings:
if (oldSelected.get(i).equalsIgnoreCase(String.valueOf(fc.getText()))){
fc.setChecked(true);
}
However, it doesn't do what I expect it to do.
How i can trim this space and get the desired results?

You need to trim the white spaces first.
String oldSelected = ",Air Conditioner,";
String newSelected = ", Air Conditioner, ";
if(oldSelected.replaceAll("\\s", "").equalsIgnoreCase(newSelected.replaceAll("\\s", ""))){
// Do Something
}
else{ // Do Something Else
}
Hope that helps! :)

You can do something like this:
public static void main(String[] args) {
String s1 = ",Air Condition";
String s2 = ", Air Condition";
System.out.println(s1.equals(s2.replace(", ", ",")));
}
or, if you want to keep space between words, you may use like this:
public static void main(String[] args) {
String s1 = ",Air Condition";
String s2 = ", Air Condition";
System.out.println(s2.split(", ")[1]);
System.out.println(s1.split(",")[1]);
System.out.println(s1.split(",")[1].equals(s2.split(", ")[1]));
}

Try,
String.valueOf(fc.getText())).replaceAll("\\s+","")
This removes all whitespaces and non-visible characters (e.g. tab, \n)

you can use String methot called SPLIT for example you have
String STR1 = "Ahoj"
String STR2 = "Ahoj "
String x[] = STR1.split(" ");
String y[] = STR2.split(" ");
then use simple for loop to check all words :)

Well, worked solution as #Rahul suggest to use .trim() but this worked with english words only, so in order to equalize all language i trim the equalized text to as below :
String checkedVal = oldSelected.get(i);
checkedVal = checkedVal.trim();
if (checkedVal.equalsIgnoreCase(String.valueOf(fc.getText().toString().trim()))){
fc.setChecked(true);
}
Thanks for all answers.

Related

Java: Checking each space in a String

I'm sure this is fairly simple, however I've tried googling the question but can't find an answer that fits my problem.
I'm playing around with string manipulation and one of the things I'm trying to do is get the first letter of each word. (And then place them all into a string)
I'm having trouble with registering each 'space' so that my If statement will be triggered. Here's what I have so far.
while (scanText.hasNext()) {
boolean isSpace = false;
if (scanText.hasNext(" ")) {isSpace = true;}
String s = scanText.next();
if (isSpace) {firstLetters += s + " ";}
}
Also, if there is a much better way to do this then please let me know
You can also split the original text by spaces, and collect the words.
String input = " Hello world aaa ";
String[] split = input.trim().split("\\s+"); // all types of whitespace; " +" to pick spaces only
// operate on "split" array containing words now: [Hello, world, aaa]
However using regexps here might be overkill.
Assuming that scanText is a Scanner object, you could use something like stated on the documentation:
Scanner s = new Scanner(input).useDelimiter("\\s+"); //regex for spaces
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Turn some alphabet to specific number in Java Netbeans

i want to make program that will turn your input text into another version.
For example like this:
If I input = "I want some coffee" , it will turn to = " 1 W4NT S0M3 C0FF33".
From this example we get that =
A will turn to 4, O will turn to 0, E will turn to 3, and I will turn to 1.
So, what code to make this program? i'm sorry i'm so noob in java.
Thank you.
There are two methods. Convert the String to uppercase(if needed). Then run a loop to iterate through the characters of the string. If the character is A,E,I,O, then add 4,3,1,0 to the string s2 else add the current character. (s1="I want some coffee").
String s1="I want some coffee";
s1=s1.toUpperCase();
String s2="";
for(int i=0;i<s1.length();i++){
char ch=s1.charAt(i);
if(ch=='A'||ch=='a')
s2+="4";
else if(ch=='O'||ch=='o')
s2+="0";
else if(ch=='E'||ch=='e')
s2+="3";;
else if(ch=='I'||ch=='i')
s2+="1";
else
s2+=ch;
}
System.out.println(s2);
Or, you can use replaceAll() method to replace all the occurences of A,E,I,O with 4,3,1,0.
public static void main(String[] args) {
String s1="I want some coffee";
s1=s1.toUpperCase();
s1=s1.replaceAll("A","4");
s1=s1.replaceAll("E","3");
s1=s1.replaceAll("I","1");
s1=s1.replaceAll("O","0");
System.out.println(s1);
}
}

String.replace isn't working

import java.util.Scanner;
public class CashSplitter {
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
System.out.println("Cash Values");
String i = S.nextLine();
for(int b = 0;b<i.length(); b ++){
System.out.println(b);
System.out.println(i.substring(0,i.indexOf('.')+3));
i.replace(i.substring(0, i.indexOf('.') + 3), "");
System.out.println(i);
System.out.println(i.substring(0, i.indexOf('.') + 3));
}
}
}
The code should be able to take a string with multiple cash values and split them up, into individual values. For example 7.32869.32 should split out 7.32, 869.32 etc
A string is immutable, therefore replace returns a new String for you to use
try
i = i.replace(i.substring(0, i.indexOf('.') + 3), "");
Although try using
https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
There are several problems with your code:
You want to add two, not three, to the index of the decimal point,
You cannot use replace without assigning back to the string,
Your code assumes that there are no identical cash values.
For the last point, if you start with 2.222.222.22, you would get only one cash value instead of three, because replace would drop all three matches.
Java offers a nice way of splitting a String on a regex:
String[] parts = S.split("(?<=[.]..)")
Demo.
The regex is a look-behind that expects a dot followed by any two characters.

How can I remove gap in String in Java

Here is my code:
package test;
public class Stringtest {
public static void main(String[] args) {
String a = " love y ou !! ";
String b = a.trim();
b.replaceAll("\\s+","");
System.out.println(b);
}
}
But the result is still:"love y ou !!". It just remove the white space at the start and the end of the string. Did I do anything wrong?
Strings are immutable which means you can't change them. That is why replaceAll doesn't affect original string, but creates new one with replaced values which you need to store somewhere, possibly even in original reference.
So try with
b = b.replaceAll("\\s+", "");
replaceAll method of String will return back string after removing all the spaces and as String is immutable, so assign the outcome of replaceAll back to b like:
b = b.replaceAll("\\s+","");//Note you dont need to trim if you want to replace every spaces.
Run the following and you'll understand what you have done.
System.out.println(b.replaceAll("\\s+",""));
string.replace() returns the replaced string
you forgot to store the substring which return from replaceAll method.
try
b = b.replaceAll("\\s+","");

Splitting String according to multiple String in java

I just beginning to learn java, so please don't mind.
I have string
String test="John Software_Engineer Kartika QA Xing Project_Manager Mark CEO Celina Assistant_Developer";
I want to splitting based of position of Company={"Software_Engineer", "QA","Project_Manager","CEO ","Assistant_Developer"};
EDITED:
if above is difficulties then is it possible??? Based or {AND, OR)
String value="NA_USA >= 15 AND NA_USA=< 30 OR NA_USA!=80"
String value1="EUROPE_SPAIN >= 5 OR EUROPE_SPAIN < = 30 "
How to split and put in hashtable in java. finally how to access it from the end. this is not necessary but my main concern is how to split.
Next EDIT:
I got solution from this, it is the best idea or not????
String to="USA AND JAPAN OR SPAIN AND CHINA";
String [] ind= new String[]{"AND", "OR"};
for (int hj = 0; hj < ind.length; hj++){
to=to.replaceAll(ind[hj].toString(), "*");
}
System.out.println(" (=to=) "+to);
String[] partsparts = to.split("\\*");
for (int hj1 = 0; hj1 < partsparts.length; hj1++){
System.out.println(" (=partsparts=) "+partsparts[hj1].toString());
}
and
List<String> test1=split(to, '*', 1);
System.out.println("-str333->"+test1);
New EDIT:
If I have this type of String how can you splitting:
final String PLAYER = "IF John END IF Football(soccer) END IF Abdul-Jabbar tennis player END IF Karim -1996 * 1974 END IF";
How can i get like this: String [] data=[John , Football(soccer) ,Abdul-Jabbar tennis player, Karim -1996 * 1974 ]
Do you have any idea???
This will split your string for you and store it in a string array(Max size 50).
private static String[]split = new String[50];
public static void main(String[] args) {
String test="John -Software_Engineer Kartika -QA Xing -Project_Manager Mark -CEO Celina -Assistant_Developer";
for (String retval: test.split("-")){
int i = 0;
split[i]=retval;
System.out.println(split[i]);
i++;
}
}
You can make a string with Name:post and space. then it will be easy get desire value.
String test="John:Software_Engineer Kartika:QA Xing:Project_Manager"
I am unable to comment as my reputation is less. Hence i am writing over here.
Your first Question of String splitting could be generalized as positional word splitting. If it is guaranteed that you require all even positioned string, you could first split the string based on the space and pull all the even position string.
On your Second Question on AND & OR split, you could replace all " AND " & " OR " with single String " " and you could split the output string by single space string " ".
On your third Question, replace "IF " & " END" with single space string " " and I am not sure whether last IF do occurs in your string. If so you could replace it too with empty string "" and then split the string based on single space string " ".
First classify your input string based on patterns and please devise an algorithm before you work on Java.
I would suggest you to use StringBuffer or StringBuilder instead of using String directly as the cost is high for String Operation when compared to the above to.
try this
String[] a = test.replaceAll("\\w+ (\\w+)", "$1").split(" ");
here we first replace word pairs with the second word, then split by space
You can take a set which have all positions Like
Set<String> positions = new HashSet<String>();
positions.add("Software_Engineer");
positions.add("QA");
String test="John Software_Engineer Kartika QA Xing Project_Manager Mark CEO Celina Assistant_Developer";
List<String> positionsInString = new ArrayList<String>();
Iterator<String> iterator = positions.iterator();
while (iterator.hasNext()) {
String position = (String) iterator.next();
if(test.contains(position)){
positionsInString.add(position);
break;
}
}

Categories