How to compare individual character that is stored in a variable in Java?
String value = "abaabb";
Now how can I know that abaabb consist of only a and b in it and no other characters like c, d, ...
For this I want a way to compare individual characters in abaabb.
You can use .charAt() method:
String x="aabbbb";
for (int i = 0; i < x.length(); i++) {
if(x.charAt(i)=='a' || x.charAt(i)=='b') {
System.out.println("a or b");
}
}
You could use String#matches with Regular Expression:
boolean valid = "abaabb".matches("[ab]+");
easiest solution:
String value = "abaabb";
Set<Character> letters = new HashSet<Character>();
for(int i = 0; i < value.length(); i++){
letters.add(value.charAt(i));
}
//Edit
#Trincot
In set we collect unique characters in string, then we can build second collection with letters to check if only 'a' and 'b' are present
Set<Character> check = new HashSet<>();
check.add('a');
check.add('b');
letters.removeAll(check);
System.out.println(letters.isEmpty());
Related
I have a String Array with multiple entries in it. I want to transcribe this String Array into another one, replacing specific entries with a digit (k in this case).
What I've tried so far:
public void replace(String[] eqh, char var, int maxX){
String[] holder = new String[eqh.length];
String comp = "";
for (int k = -maxX/2; k <= maxX/2; k++){
for (int i = 0; i< eqh.length; i++){
if (eqh[i].equals(var)){
holder[i] = ""+k;
} else {
holder[i] = eqh[i];
}
comp = Arrays.toString(holder);
System.out.println("comp: "+comp);
}
/// some stuff with comp here
}
Unfourtunatley this is not working, the return for comp is exactly the same as the input from eqh.
You are comparing strings with chars in eqh[i].equals(var) (it will always return false). If you want to check whether first char is equals to var, do eqh[i].charAt(0) == var
Also, it is not a good practice to convert integers to strings doing ""+k. Use Integer.toString(k) or String.valueOf(k).
You are trying to check if a String is equals to a char, the result of this test will always be false.
You can use eqh[i].indexOf(var) >= 0 to test if a String contains a char.
I have String variable with value- f.e.:
this is test-str-ing_łóśżćń.
And I would like replace this chars:
, -, ł,ó,ś,ż,ć,ń
with those:
_,_,l,o,s,z,c,n.
And I mean here, that if parser will found f.e.: char - (which is second in first list) should be replaced with char that is in the same position/place in second list, which in this example is: _.
The char ó should be replaced with char o.
The char ń should be replaced with char n.
In my case the list of characters to replace is quite long and parsing in loop for each char to replace would not be enought efficient.
I know method replaceAll(). but it only accept one in String and one out String
So I am looking for method, that will allow me to work on arrays/list of Strings instead of single String.
Please give me some help.
Use java.text.Normalizer to Decompose accented letters in base letter plus "combining diacritical marks."
String base = Normalizer.normalize(accented, Form.NFKD)
.replaceAll("\\p{M}", "");
This does a decompose (D) normalization, and then removes Marks.
Some replacements still needed.
char[] out = new char[src.length()];
for( j ...){
inputChar = src.charAt(j);
for (int i = 0; i < convertChars.length; i++) {
if (inputChar == convertChars[i]) {
inputChar = toChars[i];
}
}
}
out[j] = inputChar ;
}
out2 = new String(out);
Extracted from bigger code without IDE, not tested. Loop (I hope) don't allocate objects and should not degrade speed.
Make a static lookup table:
private static char[] substitutions = new char[65536];
static {
// Initialize
for (char c = 0; c < substitutions.length; c++) {
substitutions[c] = c;
}
// Now add mappings.
substitions['-'] = '_'; // Map source->target character
... // Add the rest
}
// LATER IN Code
char[] stringChars = inputString.toCharArray();
for (int i = 0; i < stringChars.length; i++) {
stringChars[i] = substitutions[stringChars[i]];
}
outputString = new String(stringChars);
I have to write code that counts how many unique letters are in a string:
e.g
"aabbcdefff"
This will return 6 as there are 6 different letters in the string. Currently I have the code:
String letters = ("aabbcdefff");
char temp = ' ';
for (int i = 0; i < letters.length(); i++){
temp = inp.charAt(i);
if (temp != ' ') { //doesnt count spaces as letters
alphabetSize = alphabetSize+1;
for (int j = 0; j < inp.length(); j++){
tempInp = tempInp.replace(temp,' ');
}
}
}
The idea of this code is that it should when detecting a letter, replace all instances of it with a space. When i run this code however, it just gives me the length of the string. What am i doing wrong? Is there another more elegant way to do this?
Thanks for your help.
You are fine by just using a Set.
Loop over your string, and add each letter to your set. afterwards, check length of your set, and your done.
It's a one-liner with Java 8 streaming API:
long numberOfDistinctChars = s.chars().distinct().count()
You can easily find it using Linq service.
Please add using System.Linq; Namespace.
string str = "TestTest";
int cnt = str.ToLower().ToCharArray().Where(w => w != ' ').Distinct().Count();
You can do it easily by using Java collection (Set).
Set<Character> result = new HashSet<Character>();
String letters = ("aabbcdefff");
for (int i = 0; i < letters.length(); i++){
result.add(letters.charAt(i));
}
Your final result is in result set and it is always unique.
Reference: http://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Thanks.
One way of doing this would be converting the string to an array and then using the following method:
String s = "aabbcdefff";
char[] charArray = s.toCharArray();
ArrayList<Character> al = new ArrayList<Character>();
for(char c : charArray){
if(al.contains(c)){
al.remove((Character)c);
}else{
al.add(c);
}
}
What ever is left in the array list 'al' are duplicates. The advantage of this method is that it has O(n) runtime
I want to use hashtable to find unique characters as it seems more efficient to me so for example, hello in hashtable would be=> {h:1,e:1,l:2,o:1} & since value is more than 1 then string isnt unique. I know I can do ascii way of counting unique characters but I want to implement the hashtable way.
Please note, I do not want a regex implementation.
static void findHashUnique(String str)
{
Hashtable<Character, Integer> ht = new Hashtable<Character, Integer>();
for(int i=0;i<str.length();i++)
{
int cnt=1;
if(!ht.containsKey(str.charAt(i)))
{
ht.put(str.charAt(i), cnt);
}
}
System.out.print(ht);
}
I am stuck at the part of how will I first initialize the hashtable & also check if value exists then increment. In case of 'l' it will increment to 2 instead of being 1 since the key is the same.
Also Is this solution efficient?
Here's my approach.
String string = "hello";
Hashtable<Character, Integer> map = new Hashtable<>();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
System.out.println(map);
Output: {e=1, o=1, l=2, h=1}
Well, I don't know exactly what character encodings you will be examining, but if you are constraining yourself to only ASCII characters, you can use a simple array of 128 elements.
public static String uniqueLetters(String s) {
// storage for ascii characters
char[] letters = new char[128];
// mark counts of all letters
for(int i = 0; i < s.length(); i++) {
letters[ (int)s.charAt(i) ]++;
}
// find unique letters
String uniques = "";
for(int i = 0; i < letters.length; i++) {
if ( letters[i] == 1 ) {
uniques += Character.toString( (char)letters[i] );
}
}
return uniques;
}
To "fix" your code, use a HashSet<Character>, which uses a Hashtable internally, but you don't have to know or worry about that. Just keep adding the chars to the set and you'll be left with a unique set of chars at the end.
To achieve the intention more easily:
String uniqueChars = str.replaceAll("(.)(?=.*\\1)", "");
I want to read a String sentence from a Textfield and compare each letter in the String to my list of already made strings which look like this:
A = 123f;
B = 221d;
H = 2333gg;
And so on..
My question is: how can i read my message as individual strings lets say this is the message: "Hello World"
i want to be able to compare every word to my strings that i have made:
so "Hello World" it would compare the first letter "H" and it would make it into what i defined "H" to be, So it would output in a JLabel or anything else as 2333gg.
Thank you in advance!
I think you need to store your letters (A = ..., B = ..., H = ...) into a Map, then you iterate through the input letters (that you can get from the input string using toCharArray()), and if the Map contains the letter as a key, you output the corresponding value. Something like this:
Map<Character, String> lettersMap = new HashMap<Character, String>();
lettersMap.put(Character.valueOf('A'), "123f");
lettersMap.put(Character.valueOf('B'), "221d");
lettersMap.put(Character.valueOf('H'), "2333gg");
String input = "Hello world";
StringBuffer sb = new StringBuffer();
char[] inputLetters = input.toCharArray();
for (int i = 0; i < inputLetters.length; i++) {
Character letter = Character.valueOf(inputLetters[i]);
if (lettersMap.containsKey(letter))
sb.append(lettersMap.get(letter));
}
System.out.println(sb.toString());
Once you have a String (let's call it myString), you can iterate through the letters like so:
for (final char c : new StringIterator(myString))
{
// Do something with each character (c)
}
Does that help?
Edit: I'm SO sorry - I was using a non standard library in a piece of code and forgot.
How about:
for (int i = 0; i < myString.length(); i++)
{
char c = myString.charAt(i);
//Process char
}
You can use String.toCharArray() to get an array of chars, where you can access each char individually.
String[] charArray = userInput.toCharArray();
for (int i = 0; i < charArray.length; i++)
{
...
}