Is there any method like char At in Dart? - java

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.

Related

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

Converting from Int to Hex in Delphi and Java

I have to convert the following Delphi code to Java:
function IntToHex(MyValue: Integer; MinimumWidth: Integer): Ansistring;
begin
AnsiStrings.FmtStr(Result, '%.*x', [MyValue, MinimumWidth]);
end;
The IntToHex function converts a DecimalValue integer into a hexadecimal format string of at least MinimumWidth characters wide.
I've implemented it in Java as:
public static String intToHex(int value)
{
return Integer.toHexString(value);
}
Do I need in Java to indicate that the resulting string must contain at least the specified number of digits like in Delphi with parameter MinimumWidth?
Did I already with my Java function implemented the full functionality from the Delphi IntToHeX-function?
If I correctly understand your question, I think your solution should be to use String.format in Java
If you want hex numbers in the string you can use
String myFormattedString = String.format("%x", mynumber);
You can specify the lenght prepending it to the x, as
String myFormattedString = String.format("%4x", mynumber);
Where of course mynumber is a int or any other kind of valid number.
If you want to pad with zeros you should use
String myFormattedString = String.format("%04x", mynumber);
You can use capital X to have capital letters in the resulting String
To have more information on the format option you can take a look at the following URL: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
Hope this can help

How do I compare each character of a String while accounting for characters with length > 1?

I have a variable string that might contain any unicode character. One of these unicode characters is the han 𩸽.
The thing is that this "han" character has "𩸽".length() == 2 but is written in the string as a single character.
Considering the code below, how would I iterate over all characters and compare each one while considering the fact it might contain one character with length greater than 1?
for ( int i = 0; i < string.length(); i++ ) {
char character = string.charAt( i );
if ( character == '𩸽' ) {
// Fail, it interprets as 2 chars =/
}
}
EDIT:
This question is not a duplicate. This asks how to iterate for each character of a String while considering characters that contains .length() > 1 (character not as a char type but as the representation of a written symbol). This question does not require previous knowledge of how to iterate over unicode code points of a Java String, although an answer mentioning that may also be correct.
int hanCodePoint = "𩸽".codePointAt(0);
for (int i = 0; i < string.length();) {
int currentCodePoint = string.codePointAt(i);
if (currentCodePoint == hanCodePoint) {
// do something here.
}
i += Character.charCount(currentCodePoint);
}
The String.charAt and String.length methods treat a String as a sequence of UTF-16 code units. You want to treat the string as Unicode code-points.
Look at the "code point" methods in the String API:
codePointAt(int index) returns the (32 bit) code point at a given code-unit index
offsetByCodePoints(int index, int codePointOffset) returns the code-unit index corresponding to codePointOffset code-points from the code-unit at index.
codePointCount(int beginIndex, int endIndex) counts the code-points between two code-unit indexes.
Indexing the string by code point index is a bit tricky, especially if the string is long and you want to do it efficiently. However, it is a do-able, albeit that the code is rather cumbersome.
#sstan's answer is one solution.
This will be simpler if you treat both the string and the data you're searching for as Strings. If you just need to test for the presence of that character:
if (string.contains("𩸽") {
// do something here.
}
If you specifically need the index where that character appears:
int i = string.indexOf("𩸽");
if (i >= 0) {
// do something with i here.
}
And if you really need to iterate through every code point, see How can I iterate through the unicode codepoints of a Java String? .
An ASCII character takes half the amount a Unicode char does, so it's logical that the han character is of length 2. It not an ASCII char, nor a Unicode letter. If it were the second case, the letter would be displayed correctly.

Getting last few characters from a string

I have a java string containing n number of characters.
How do I extract the LAST few characters from that string?
I found this piece of code online that extracts the first few, but I dont understand it so I cant modify it.
Can anyone help me with this?
String upToNCharacters = s.substring(0, Math.min(s.length(), n));
Try,
String upToNCharacters = s.substring(s.length()-lastCharNumber);
That piece of code does exactly the opposite of what you want. Now let's see why and how we can modify it.
Quick solution
You can modify the code as follows to do what you want:
String lastNchars = s.substring( Math.max(0, s.length()-n));
Explanation
According to the official documentation, Java String class has a special method called substring().
The signature of the method is the following (with overload):
public String substring(int beginIndex, int endIndex))
public String substring(int beginIndex)
The first method accepts 2 parameters as input:
beginIndex: the begin index of the substring, inclusive.
endIndex: the end index of the substring, exclusive.
The second overload will automatically consider as endIndex the length of the string, thus returning "the last part"
Both methods return a new String Object instance according to the input parameters just described.
How do you pick up the right sub-string from a string? The hint is to think at the strings as they are: an array of chars. So, if you have the string Hello world you can logically think of it as:
[H][e][l][l][o][ ][w][o][r][l][d]
[0]...............[6]......[9][10]
If you choose to extract only the string world you can thus call the substring method giving the right "array" indexes (remember the endIndex is exclusive!):
String s = "Hello world";
s.substring(6,11);
In the code snippet you provided, you give a special endIndex:
Math.min(s.length(), n);
That is exactly up to the n th char index taking into account the length of the string (to avoid out of bound conditions).
What we did at the very beginning of this answer was just calling the method and providing it with the beginning index of the substring, taking into account the possible overflow condition if you choose a wrong index.
Please note that any String Object instance can take advantage of this method, take a look at this example, for instance:
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);
As you see even "abc", of course, has the substring method!
Have a look at the substring documentation, Basically what it does is, it returns a substring of the string on which it is called, where substring from the index specified by the first parameter and the ends at the second parameter.
So, to get the last few characters, modify the begin index and the end index to the values you need. There is also another version of this method which takes only one parameter, just the begin index, which might be useful for you.
String lastNchars = s.substring(s.length()-n);
One of the String.substring() overloads takes one parameter - the index of the starting index. From that, you can easily implement your function :
String lastFew(String s, int number) {
if (number > s.length()) {
throw new IllegalArgumentException("The string is too short!");
} else return s.substring(s.length()-number);
}

Character literal in Java?

So I just started reading "Java In A Nutshell", and on Chapter One it states that:
"To include a character literal in a Java program, simply place it between single quotes"
i.e.
char c = 'A';
What exactly does this do^? I thought char only took in values 0 - 65,535. I don't understand how you can assign 'A' to it?
You can also assign 'B' to an int?
int a = 'B'
The output for 'a' is 66. Where/why would you use the above^ operation?
I apologise if this is a stupid question.
My whole life has been a lie.
char is actually an integer type. It stores the 16-bit Unicode integer value of the character in question.
You can look at something like http://asciitable.com to see the different values for different characters.
In Java char literals represent UTF-16 (character encoding schema) code units. What you got from UTF-16 is mapping between integer values (and the way they are saved in memory) with corresponding character (graphical representation of unit code).
You can enclose characters in single quotes - this way you don't need to remember UTF-16 values for characters you use. You can still get the integer value from character type and put if for example in int type (but generally not in short, they both use 16 bits but short values are from -32768 to 32767 and char values are from 0 to 65535 or so).
If you look at an ASCII chart, the character "A" has a value of 41 hex or 65 decimal. Using the ' character to bracket a single character makes it a character literal. Using the double-quote (") would make it a String literal.
Assigning char someChar = 'A'; is exactly the same as saying char someChar = 65;.
As to why, consider if you simply want to see if a String contains a decimal number (and you don't have a convenient function to do this). You could use something like:
bool isDecimal = true;
for (int i = 0; i < decString.length(); i++) {
char theChar = decString.charAt(i);
if (theChar < '0' || theChar > '9') {
isDecimal = false;
break;
}
}

Categories

Resources