I have a List and I would like to split the first two characters (alpha characters) into a different string and then all the numbers that follow (they vary in length).
How could I do that?
String wholeString == "AB4578";
String alpha; // this has to be AB
String num; // this has to be 4578
Thank you very much in advance!
Tested and works:
String wholeString = "AB4578";
String alpha = null;
String num = null;
for (int i = 0; i < wholeString.length(); i++) {
if (wholeString.charAt(i) < 65) {
alpha = wholeString.substring(0, i);
num = wholeString.substring(i);
break;
}
}
With this approach both the A-z part and the 0-9 part can vary in size, it might not be very effective though considering it's calling charAt(...) for every char in the String.
Hope this helps.
String wholeString = "AB4578";
String alpha = wholeString.substring(0,2);
String num = wholeString.substring(2);
Must See
String.substring(int, int)
If the format is the same, then the answer is already provided. But if the format is not same than you can convert the string into char array and check each character against the ASCII values to check if it is an alphabet or a number.
char[] ch=wholestring.toCharArray();
Now you can apply a for loop for checking each character individually.
for(int l=0; l<ch.length;l++)
{
//code to check the characters
}
And you can separate both types in different strings using StringBuilder or forming two char arrays and then converting them to strings using
String.valueOf(chArray);
ASCII values - http://www.asciitable.com/
Try using the substring method for Strings.
Example:
String alpha = wholeString.substring(0,2);
String num = wholeString.substring(2);
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#substring%28int%29
If the format is always the same you can just do this:
String wholeString = "AB4578";
String alpha = wholeString.substring(0, 2);
String num = wholeString.substring(2);
Recommend String API. You would need to use substring operations.
Related
For example I want to concatanate char a ='A' and int b = 5 into string = "A5".
String string = a + b; doesn't work.
You may want to use StringBuilder, where you can append any type of primitives :
char a ='A';
int b = 5;
StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
String result = sb.toString();
The easiest way for me is to precede the String with an empty String.
String str = "" + 'a' + 10;
The conversion goes from left to right so you start out with a String.
If you do it this way,
String str = 'a' + 10 + "";
you will get a String value of "107" since the numeric addition is done before the conversion to a String.
One way to convert most primitive values to String is to utilize the overloaded method in the String class valueOf():
public static void main(String[] args)
{
char a = 'A';
int b = 5;
String str = String.valueOf(a) + b; //Can do either of these two lines, will work the same
String str2 = a + String.valueOf(b);
System.out.println(str);
System.out.println(str2);
}
You only need to convert one of the values into String, because appending them afterward will automatically convert the other into a String.
This method will work on both char, and int in this scenario, but will also work on long, double, float and boolean as well. This is identical to calling Integer.toString(int i) or Character.toString(i) etc... but it is convenient to be able to use the same overloaded method for each case instead of requiring to call methods from different classes.
To all the answers already given I provide one that explain why "it doesn´t work" as you expect. A string is nothing but an immutable collection of char. A char itself is nothing but a (signed) integer and thus can implicitely converted to such. Thus when you write char+ int an integer-operation occurs, in your case A + 5 which results in 70, because ASCII-code for A is 65.
Last but not least String s = 70 surely does not compile, because a number can´t be converted to a string.
So you have to tell the compiler that you do not want an integer-operation, but a string-concatenation, which is by turning one of the operands into a string already:
String s = 'A'.toString() + 5
or
String s = 'A' + 5.toString()
Below is a snippet of my java code.
//converts a binary string to hexadecimal
public static String binaryToHex (String binaryNumber)
{
BigInteger temp = new BigInteger(binaryNumber, 2);
return temp.toString(16).toUpperCase();
}
If I input "0000 1001 0101 0111" (without the spaces) as my String binaryNumber, the return value is 957. But ideally what I want is 0957 instead of just 957. How do I make sure to pad with zeroes if hex number is not 4 digits?
Thanks.
You do one of the following:
Manually pad with zeroes
Use String.format()
Manually pad with zeroes
Since you want extra leading zeroes when shorter than 4 digits, use this:
BigInteger temp = new BigInteger(binaryNumber, 2);
String hex = temp.toString(16).toUpperCase();
if (hex.length() < 4)
hex = "000".substring(hex.length() - 1) + hex;
return hex;
Use String.format()
BigInteger temp = new BigInteger(binaryNumber, 2);
return String.format("%04X", temp);
Note, if you're only expecting the value to be 4 hex digits long, then a regular int can hold the value. No need to use BigInteger.
In Java 8, do it by parsing the binary input as an unsigned number:
int temp = Integer.parseUnsignedInt(binaryNumber, 2);
return String.format("%04X", temp);
The BigInteger becomes an internal machine representation of whatever value you passed in as a String in binary format. Therefore, the machine does not know how many leading zeros you would like in the output format. Unfortunately, the method toString in BigInteger does not allow any kind of formatting, so you would have to do it manually if you attempt to use the code you showed.
I customized your code a bit to include leading zeros based on input string:
public static void main(String[] args) {
System.out.println(binaryToHex("0000100101010111"));
}
public static String binaryToHex(String binaryNumber) {
BigInteger temp = new BigInteger(binaryNumber, 2);
String hexStr = temp.toString(16).toUpperCase();
int b16inLen = binaryNumber.length()/4;
int b16outLen = hexStr.length();
int b16padding = b16inLen - b16outLen;
for (int i=0; i<b16padding; i++) {
hexStr=('0'+hexStr);
}
return hexStr;
}
Notice that the above solution counts up the base16 digits in the input and calculates the difference with the base16 digits in the output. So, it requires the user to input a full '0000' to be counted up. That is '000 1111' will be displayed as 'F' while '0000 1111' as '0F'.
I want to allow a user specify a Unicode range via an XML config file. E.g. they could state 0100..017F as the range. For my (Java) app to consume this char range, I need to convert the XML input (String) to type char. Any ideas?#
E.g.
String input = "0100..017F"; // I can change format of input, if enables a solution
char from = '\u0100';
char to = '\u017f';
Thanks.
If it always matches exactly that format, then this will suffice:
char from = (char)Integer.parseInt(input.substring(0, 4), 16);
char to = (char)Integer.parseInt(input.substring(6), 16);
For something more flexible:
char from;
char to;
java.util.regex.Matcher m = java.util.regex.Pattern.compile(
"^([\\da-fA-F]{1,4})(?:\\s*\\.\\.\\s*([\\da-fA-F]{1,4}))?$").matcher(input);
if (!m.find()) throw new IllegalArgumentException();
from = (char)Integer.parseInt(m.group(1), 16);
if (m.group(2) != null) {
to = (char)Integer.parseInt(m.group(2), 16);
} else {
to = from;
}
That allows for 1 to 4 hex digits for each character, the .. may have space around it, and the to part of the range may be omitted and assumed to be equal to from.
I have a String which contains hex values. Now i want to write this exact string to a file with the ending .hex . How can i realize this in java?
I already tried to convert the Hex Values into ASCII and then write this string into a file.
But all Hex Values which are higher then 127(dec) can't be processed correctly.
86(hex) is transformed to ?(char), which is 3F(hex) and not 86(hex).
You can try to take each char of your string, convert it to integer and then write values in bytes in a file. To do the opposite process, you just have to read the file into a byte array and convert each byte into a char to retrieve your string. Then I'm sure you can find some algorithm to cast your string into Hex string.
For me the Answer was this:
Under Projectproperties i needed to set the Text-file-Encoding to ISO-8859-1.
Then my old procedure worked very well.
public static String hexToASCII(String hex){
if(hex.length()%2 != 0){
System.err.println("requires EVEN number of chars");
return null;
}
StringBuilder sb = new StringBuilder();
for( int i=0; i < hex.length()-1; i+=2 ){
String output = hex.substring(i, (i + 2));
int decimal = Integer.parseInt(output, 16);
sb.append((char)decimal);
}
return sb.toString();
}
So I have a set of base digits like "BCDFGHJKLMNPQRSTVWXZ34679"
how do I convert a value say "D6CN96W6WT" to binary string in Java?
This should work (assuming 0,1 for you binary digits):
// your arbitrary digits
private static final String DIGITS = "BCDFGHJKLMNPQRSTVWXZ34679";
public String base25ToBinary(String base25Number) {
long value = 0;
char[] base25Digits = base25Number.toCharArray();
for (char digit : base25Digits) {
value = value * 25 + DIGITS.indexOf(digit);
}
return Long.toString(value, 2);
}
Off the top of my head, for base-25 strings.
Integer.toString(Integer.valueof(base25str, 25), 2)
Its a little unclear from your question whether you're talking about actual 0-9-Z bases, or a number encoding with an arbitrary list of symbols. I'm assuming the first, if its the later then you're out of luck on built-ins.