String with one character can be casted to char? - java

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);
}

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.

Using a For Loop to set all lower case to uppercase

How do you use a for loop to set all the lower cases of a string into upper cases?
This is what I did, but I get two compiler errors,
The method setCharAt(int, char) is undefined for the type
java.lang.String [line 7]
Array cannot be resolved [line 12]
public static String allUpperCases(String toEncode){
int length = toEncode.length();
for (int i = 0; i < length; i++){
char ch = toEncode.charAt(i);
if (Character.isLowerCase(ch)){
toEncode.setCharAt(i, Character.toUpperCase(ch));
}
}
return toEncode;
}
You can just use a single operation!
my_string = my_string.toUpperCase();
If you just want your String all uppercase, there is a function in Java:
yourstring.toUpperCase();
You don't need to use a for loop to set a string to lower or upper case. You can use myString = myString.toLowerCase();. Conversely, there is the opposite: myString = myString.toUpperCase();. You should really read the String API.
With regards to your errors:
The String type does not have a setCharAt() function in Java. That's because a String, at least in Java, is an immutable type. When you "change" a string, unless you're using a StringBuilder or modifying the underlying char array, you are actually assigning a new String to the variable.
I can't diagnose your Array cannot be resolved error, as I don't see an array in your code.

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

How to assign a single char to a TextView

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

Categories

Resources