How to assign a single char to a TextView - java

I'm trying to assign a single char to a TextView in Android Java.
Using a string works:
textView.setText("X");
But using a char aborts at runtime:
textView.setText('X');
and:
char Key5 = 'X';
textView.setText(Key5);
Using a Character also aborts at runtime:
Character Key5 = 'X';
textView.setText(Key5);
Typecasting the Character to a string does work:
Character Key5 = 'X';
textView.setText(Key5.toString());
How do I assign a plain char variable to a TextView?

You can "convert" a character into a String with the method String.valueOf(char):
char key = 'X';
textView.setText(String.valueOf(key));

Short answer:
You can't, you must use a CharSequence. (Thanks Sam)
Long answer:
The problem is that TextView.setText is not overloaded to take a character as the only parameter. It can only take a CharSequence.
From the CharSequence documentation
This interface represents an ordered set of characters and defines the methods to probe them.
String works because it implements the CharSequence inteface. It doesn't make sense to have a CharSequence that only holds one character

Related

Is there any method like char At in Dart?

String name = "Jack";
char letter = name.charAt(0);
System.out.println(letter);
You know this is a java method charAt that it gives you a character of a String just by telling the index of the String. I'm asking for a method like this in Dart, does Dart have a method like that?
You can use String.operator[].
String name = "Jack";
String letter = name[0];
print(letter);
Note that this operates on UTF-16 code units, not on Unicode code points nor on grapheme clusters. Also note that Dart does not have a char type, so you'll end up with another String.
If you need to operate on arbitrary Unicode strings, then you should use package:characters and do:
String name = "Jack";
Characters letter = name.characters.characterAt(0);
print(letter);
Dart has two operations that match the Java behavior, because Java prints integers of the type char specially.
Dart has String.codeUnitAt, which does the same as Java's charAt: Returns an integer representing the UTF-16 code unit at that position in the string.
If you print that in Dart, or add it to a StringBuffer, it's just an integer, so print("Jack".codeUnitAt(0)) prints 74.
The other operations is String.operator[], which returns a single-code-unit String. So print("Jack"[0]) prints J.
Both should be used very judiciously, since many Unicode characters are not just a single code unit. You can use String.runes to get code points or String.characters from package characters to get grapheme clusters (which is usually what you should be using, unless you happen to know text is ASCII only.)
You can use
String.substring(int startIndex, [ int endIndex ])
Example --
void main(){
String s = "hello";
print(s.substring(1, 2));
}
Output
e
Note that , endIndex is one greater than startIndex, and the char which is returned is present at startIndex.

String with one character can be casted to char?

String message = "a";
char message1 = (char) message;
System.out.println(message1);
Gives me an output error,
This should be converted with ease because the string is one character "a"
I know I can do it explicitly sorry, why the two are incompatible to cast if they are storing the same (only one character)?
As you've seen, no, you cannot cast a single character String to a char. But you could extract it explicitly:
String message = "a";
char message1 = message.charAt(0);
No you cannot do that. You can cast a char to Character because the Character object type is the "boxed" version of the char base type.
Character charObject = (Character) 'c';
char charBase = (char) charObject;
actually, because of auto-boxing and auto-unboxing, you don't need the explicit cast:
Character charObject = 'c';
char charBase = charObject;
However, a String is an object type much like any other object type. That means you cannot cast it to char, you need to use the charAt(int index) method to retrieve characters from it.
Beware though that you may want to use codePointAt(int index) instead, since Unicode code points may well extend out of the 65536 code points that can be stored in the 16 bits that a char represents. So please make sure that no characters defined in the "supplementary planes" are present in your string when using charAt(int index).
As in Java any type can be converted to String, it is possibly to directly append characters to a string though, so "strin" + 'g' works fine. This is also because the + operator for String is syntactic sugar in Java (i.e. other objects cannot use + as operator, you would have to use a method such as append()). Do remember that it returns a new string rather than expanding the original "strin" string. Java strings are immutable after all.
You cannot cast a String to a char. Below is a snippet to always pick the first character from the String,
char c = message.charAt(0);
In case you want to convert the String to a character array, then it can be done as,
String g = "test";
char[] c_arr = g.toCharArray(); // returns a length 4 char array ['t','e','s','t']
A String with one char is more akin to a char[1]. Regardless, retrieve the character directly:
String ex = /* your string */;
if (!ex.isEmpty()) {
char first = ex.charAt(0);
}

when finding whether a character is in a string or not error occurs

I try to use contains method to find whether a character is in a string or not?
I get the error :
method contains in class String cannot be applied to given types
if(str.contains(ch))
required:CharSequence
found:char
code :
str1=rs.getString(1);
int len=str1.length();
while(i<len)
{
char ch=str1.charAt(i);
if (str.contains(ch))
continue;
else
str=str+str1.charAt(i);
i++;
}
if ( str.indexOf( ch ) != -1 ) should work.
String.contains only accepts a CharSequence, but one Character is not a CharSequence. The way above works for Characters, too. Another way, as other people have posted (but I want to explain a little bit more), would be to make your single Character into a CharSequence, for example by creating a String...
String x = "" + b; // implicit conversion
String y = Character.valueOf(ch).toString(); // explicit conversion
This is because the String has not any overloaded contains() method for char.
Use the String.contains() method for CharSequence like -
String ch = "b";
str.contains(ch);
Her the CharSequence is an interface. A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences.
All known implementation of at JDK are: CharSequence are - CharBuffer, Segment, String, StringBuffer, StringBuilder.
Following is the declaration for java.lang.String.contains() method
public boolean contains(CharSequence s)
So you have to Convert the character to string before passing it to the function
Character ch = 'c';
str.contains(ch.toString());//converts ch to string and passes to the function
or
str.contains(ch+"");//converts ch to string and passes to the function
Correct Code
str1=rs.getString(1);
int len=str1.length();
while(i<len)
{
char ch=str1.charAt(i);
if (str.contains(ch+""))//changed line
continue;
else
str=str+str1.charAt(i);
i++;
}

How to replace some character in a string with a single character of type char?

As an example I have abcdbab and I want to replace all ab with A.
The output is AcdbA.
I try this one but it gives an error.
char N = 65;
String S = "abcdbab";
S = S.replaceAll("ab", N);
System.out.print(S);
Is there any method to do this?
Use String.replace(CharSequence,CharSequence) (remember String is immutable, so either use the result or assign it back) like
String str = "abcdbab";
System.out.println(str);
str = str.replace("ab", "A");
System.out.println(str);
Output is
abcdbab
AcdbA
Just change the following line:
char N = 65;
to
String N = "A";
and it'll work fine.
There is no such method String#replace(CharSequence, char), you will need to find the one that is closes to your needs and adjust to it, for example, there is a String#replaceAll(CharSequence, CharSequence) method and char can be represented as a CharSequence (or a String), for example...
S = S.replaceAll("ab", Character.toString(N));
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
You can also change
S = S.replaceAll("ab", N);
to
S = S.replaceAll("ab", "" + N);
referencing here, http://www.tutorialspoint.com/java/java_string_replaceall.htm replaceAll takes a String, String not String, Char

Java string split without space

I'm trying to split some user input. The input is of the form a1 b2 c3 d4.
For each input (eg; a1), how do I split it into 'a' and '1'?
I'm familiar with the string split function, but what do I specify as the delimiter or is this even possible?
Thanks.
You could use String#substring()
String a1 = "a1"
String firstLetterStr = a1.substring(0,1);
String secondLetterStr = a1.substirng(1,a1.length());
Similarly,
String c31 = "c31"
String firstLetterStr = c31.substring(0,1);
String secondLetterStr = c31.substirng(1,c31.length());
If you want to split the string generically (rather than trying to count characters per the other answers), you can still use String.split(), but you have to utilize regular expressions. (Note: This answer will work when you have strings like a1, a2, aaa333, etc.)
String ALPHA = "\p{Alpha}";
String NUMERIC = "\d";
String test1 = "a1";
String test2 = "aa22";
ArrayList<String> alpha = new ArrayList();
ArrayList<String> numeric = new ArrayList();
alpha.add(test1.split(ALPHA));
numeric.add(test1.split(NUMERIC));
alpha.add(test2.split(ALPHA));
numeric.add(test2.split(NUMERIC));
At this point, the alpha array will have the alpha parts of your strings and the numeric array will have the numeric parts. (Note: I didn't actually compile this to test that it would work, but it should give you the basic idea.)
it really depends how you're going to use the data afterwards, but besides split("") or accessing individual characters by index, one other way to split into individual character is toCharArray() -- which just breaks the string into an array of characters...
Yes, it is possible, you can use split("");
After you split user input into individual tokens using split(" "), you can split each token into characters using split("") (using the empty string as the delimiter).
Split on space into an array of Strings, then pull the individual characters with String.charAt(0) and String.charAt(1)
I would recommend just iterating over the characters in threes.
for(int i = 0; i < str.length(); i += 3) {
char theLetter = str.charAt(i);
char theNumber = str.charAt(i + 1);
// Do something
}
Edit: if it can be more than one letter or digit, use regular expressions:
([a-z]+)(\d+)
Information: http://www.regular-expressions.info/java.html

Categories

Resources