I have to extract only numeric values from String str="sdfvsdf68fsdfsf8999fsdf09".
How can I extract numbers from an alpha numeric string in android?
String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");
update:
String str="fgdfg12°59'50\" Nfr | gdfg: 80°15'25\" Efgd";
String[] spitStr= str.split("\\|");
String numberOne= spitStr[0].replaceAll("[^0-9]", "");
String numberSecond= spitStr[1].replaceAll("[^0-9]", "");
public static String getOnlyNumerics(String str) {
if (str == null) {
return null;
}
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < str.length() ; i++) {
c = str.charAt(i);
if (Character.isDigit(c)) {
strBuff.append(c);
}
}
return strBuff.toString();
}
public static int extractNumberFromAnyAlphaNumeric(String alphaNumeric) {
alphaNumeric = alphaNumeric.length() > 0 ? alphaNumeric.replaceAll("\\D+", "") : "";
int num = alphaNumeric.length() > 0 ? Integer.parseInt(alphaNumeric) : 0; // or -1
return num;
}
You can set the value to 0 or -1 (what to do if no number is found in the alphanumeric at all) as per your needs
Related
I'm trying to encrypt a message by the following code above.
Compare 2 string length and refill the short one with cycle back.
Convert that 2 string into a binary string.
XOR that 2 binary string to get another binary string.
convert the last binary string to hexadecimal.
Issue is on the last step. The output should be 111c0d131e1c180e1b10425655 instead of 111cd131e1c18e1b10425655.
Why my output missing two letters 0?
Can anyone help me to fix, please?
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main
{
public static String StringToBinary(String str)
{
StringBuilder result = new StringBuilder();
char[] ch = str.toCharArray();
for (char character : ch)
{
result.append(String.format("%8s", Integer.toBinaryString(character)).replaceAll(" ", "0"));
}
return result.toString();
}
public static String XOR(String message, String password)
{
String tmp="";
for (int i = 0; i < message.length(); i++)
{
if (message.charAt(i) == password.charAt(i))
tmp += "0";
else
tmp += "1";
}
return tmp;
}
public static String convertBinaryToHexadecimal(String binaryStr)
{
return new BigInteger(binaryStr, 2).toString(16);
}
public static void main(String[] args)
{
int idx=0;
String msg = "poiuytrewq123";
String pwd = "asdfghjkl";
for(char m:msg.toCharArray())
{
idx = (idx < pwd.length()) ? idx : 0;
char p = pwd.charAt(idx);
idx++;
String stringOfMessageCharArray = String.valueOf(m);
String stringOfPasswordCharArray = String.valueOf(p);
String messageBinaryString = StringToBinary(stringOfMessageCharArray);
String passwordBinaryString = StringToBinary(stringOfPasswordCharArray);
String XorString = XOR(messageBinaryString,passwordBinaryString);
String cipherText = convertBinaryToHexadecimal(XorString);
System.out.print(cipherText);
}
}
}
The problem is that the number you are trying to convert from binary to hex is too small to require 2 characters, so it outputs just one.
public static String convertBinaryToHexadecimal(String binaryStr)
{
String hex = new BigInteger(binaryStr, 2).toString(16);
return hex.length() < 2 ? "0" + hex : hex;
}
If you change the function to this, it will put a 0 at the front of the hex if the length is less than 2, and return the right hex.
I have string H2SO4 for example, how can i parse to int 4 after O? I can't use substring(4), because user can type for example NH3PO4 and there 4 is substring(5), so how can I parse any character that is exactly after O?
Thanks for help.
Your question is not clear, but this may work for your case.
String str="NH3PO4";
int lastChar=str.lastIndexOf("O");//replace "O" into a param if needed
String toParse=str.substring(lastChar+1);
System.out.println("toParse="+toParse);
try{
System.out.println("after parse, " +Integer.parseInt(toParse));
}
catch (NumberFormatException ex){
System.out.println(toParse +" can not be parsed to int");
}
}
I think you need to split your String to char array' and then search the 'o' in that array:
String str = "H2SO4";
char[] charArray = str.toCharArray();
Then you got : [H, 2, S, O, 4], and you can search the "O" in this array.
Hope it helped!
There are multiple ways, all of them very simple and taken from Official documentation on String.
//Find character index of O, and parse next character as int:
int index = str.indexOf("O");
Integer.parseInt(str.subString(index, index+1));
//loop trough char array and check each char
char[] arr = str.toCharArray();
for(char ch : arr){
if(isNumber(ch){..}
}
boolean isNumber(char ch){
//read below
}
refer to ascii table and here
you can use regular expression.
.*O([0-9]+).*
And use group to extract the number proceeding character O.
Find out more here:
http://docs.oracle.com/javase/tutorial/essential/regex/groups.html
final int numAfterO;
final String strNum;
final int oIndex = chemicalName.lastIndexOf("O");
if (oIndex >= 0 && chemicalName.length() >= oIndex + 2) {
strNum = chemicalName.subString(oIndex, oIndex + 1);
} else {
strNum = null;
}
if (strNum != null) {
try {
numAfterO = Integer.parseInt(strNum);
} catch (NumberFormatException e) {
numAfter0 = -1;
}
}
android.util.Log.d("MYAPP", "The number after the last O is " + numberAfterO);
I assume this is what you want.
In order to parse every character after exactly O you can use the follow code:
char [] lettersArray = source.toCharArray();
for(int i =0 ;i<lettersArray.length;i++){
if(Character.isLetter(lettersArray[i])){
if(lettersArray[i]=='O'){
try{
int a = Interger.parseInteger(lettersArray[i].toString());
}catch(Exception e){
e.printStackTrace();
}
}
}
}
Convert the String to a char array:
String molecule = "H2SO4 ";
char[] moleculeArray = str.toCharArray();
for(int i = 0; i < moleculeArray.length; i++){
if(Character.isLetter(moleculeArray[i])){
//Huston we have a character!
if(i+1 < moleculeArray.length && Character.isDigit(moleculeArray[i+1]) {
int digit = Character.getNumericValue(Character.isDigit(moleculeArray[i+1]);
//It has a digit do something extra!
}
}
}
then iterate over the array and use Character.isDigit(c) and Character.isLetter(c)
Here's something that parses an entire molecule structure. This one parses integers > 9 as well.
public static class Molecule {
private List<MoleculePart> parts = new ArrayList<MoleculePart>();
public Molecule(String s) {
String name = "";
String amount = "";
for (char c : s.toCharArray()) {
if (inBetween(c, 'A', 'Z')) {
if (!name.isEmpty()) // first iteration, the name is still empty. gotta omit.
save(name, amount);
name = "";
amount = "";
name += c; //add it to the temporary name
}
else if (inBetween(c, 'a', 'z'))
name += c; //if it's a lowercase letter, add it to the temporary name
else if (inBetween(c, '0', '9'))
amount += c;
}
save(name, amount);
}
public String toString() {
String s = "";
for (MoleculePart part : parts)
s += part.toString();
return s;
}
//add part to molecule structure after some parsing
private void save(String tmpMoleculename, String amount) {
MoleculePart part = new MoleculePart();
part.amount = amount.isEmpty() ? 1 : Integer.parseInt(amount);
part.element = Element.valueOf(tmpMoleculename);
parts.add(part);
}
private static boolean inBetween(char c, char start, char end) {
return (c >= start && c <= end);
}
}
public static class MoleculePart {
public Element element;
public int amount;
public String toString() {
return element.name() + (amount > 1 ? amount : "");
}
}
public static enum Element {
O, S, H, C, Se, Ni //add as many as you like
}
public static void main(String[] args) {
System.out.println(new Molecule("Ni84OH43Se"));
}
I have 2 strings :
first= "BSNLP"
second = "PBN" (or anything that user enters).
Requirement is , O/P should return me the string with only those characters in first but not in second.
Eg. in this case O/P is SL
Eg2.
first = "ASDR"
second = "MRT"
, o/p = "ASD"
For this, the coding I have developed:
String one = "pnlm";
String two ="bsnl";
String fin = "";
for(int i =0; i<one.length();i++)
{
for(int j=0;j<two.length();j++)
{
//System.out.print(" "+two.charAt(j));
if(one.charAt(i) == two.charAt(j))
{
fin+=one.charAt(i);
}
}
}
ch=removeDuplicates(fin);
System.out.print(" Ret ::"+fin);
System.out.println("\n Val ::"+ch);
CH gives me the string with equal characters, but using this logic i cant get the unequal characters.
Can anyone please help?
You can use the Set interface to add all the second array of character so you can check it there later.
sample:
String one = "ASDR";
String two ="MRT";
StringBuilder s = new StringBuilder();
Set<Character> set = new HashSet<>();
for(char c : two.toCharArray())
set.add(c); //add all second string character to set
for(char c : one.toCharArray())
{
if(!set.contains(c)) //check if the character is not one of the character of second string
s.append(c); //append the current character to the pool
}
System.out.println(s);
result:
ASD
I have simple exchange your logic, see:
String one = "pnlm";
String two = "bsnl";
String fin = "";
int cnt;
for (int i = 0; i < one.length(); i++) {
cnt = 0; // zero for no character equal
for (int j = 0; j < two.length(); j++) {
// System.out.print(" "+two.charAt(j));
if (one.charAt(i) == two.charAt(j)) {
cnt = 1; // ont for character equal
}
}
if (cnt == 0) {
fin += one.charAt(i);
}
}
System.out.print(" Ret ::" + fin);
o/p: Ret ::pm.
public static void main(String[] args)
{
String one = "ASDR";
String two ="MRT";
String fin = unique(one, two);
System.out.println(fin);
}
private static String unique(final String one,
final String two)
{
final List<Character> base;
final Set<Character> toRemove;
final StringBuilder remaining;
base = new ArrayList<>(one.length());
toRemove = new HashSet<>();
for(final char c : one.toCharArray())
{
base.add(c);
}
for(final char c : two.toCharArray())
{
toRemove.add(c);
}
base.removeAll(toRemove);
remaining = new StringBuilder(base.size());
for(final char c : base)
{
remaining.append(c);
}
return (remaining.toString());
}
Iterate over the first string
For each character, check if the second string contains it
If it doesn't, add the caracter to a StringBuilder
Return stringBuilder.toString()
I need to replace a repeated char with $% followed by the char followed by $%.
e.g. "HELLO" will become "HE$%L$%O"
The following code that I wrote gives "HE$%L$%LO".
Please guide
int index=0;
String str1="";
String str2="";
String str4="";
String str5="";
for(int i=0;i<str.length();i++) {
char ch=str.charAt(i);
index=str.indexOf(ch);
if(index!=i) {
str4="$%"+str.charAt(index)+ "$%";
str1=str.charAt(index)+str5;
str2=str.replaceFirst(str1,str4);
}
}
return str2;
It looks like there's code missing because i can't see the duplicate character check, but what you want to do is go through str5 before you concat it and strip off all of the duplicate characters that are at the beginning. Then concat to your String.
Here a solution: Id solves the case if duplicates are more than 2 too. So remove all duplicates:
public class Converter {
public static void main(String[] args) {
final String result = replace("HELLO");
System.out.println("result = " + result);
}
private static String replace(String data) {
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < data.length();) {
int j = i + 1;
while (j < data.length() && data.charAt(i) == data.charAt(j)) {
j++;
}
if(j > i + 1) { // exist duplicate
stringBuilder.append("$%").append(data.charAt(i)).append("$%");
} else {
stringBuilder.append(data.charAt(i));
}
i = j;
}
return stringBuilder.toString();
}
}
And the result is:
result = HE$%L$%O
I have a string line like the following :
A:B:C:D:E:F:G:H:I:J:K:L:M
It means delimiter ( : ) count is 12 . This line is valid.
Now suppose you have a following line :
A:B:C:D:E:F:G:H:::::
This line is also valid because it contains 12 delimiter . where 8 values are present and 4 values are blank.
Now the following line should be invalid :
A:B:C:D:E:F: -- Invalid - because it contains only 6 values but expected are 12.
how to do this .. ? I tried the following code , but not getting the desired output :
String strLine = "A:B:C:D:E:F:G:H:::::" ;
int delimiterCount = 12 ;
String[] ValuesArray = strLine.split(":");
if(ValuesArray.length != delimiterCounter){
System.out.println(Invalid);
}else {
System.out.println("ValidLine");
}
I am getting the output as Invalid where as it sould be Valid.
Use following method to count occurance of particular String
public static int countOccurance(String inputString, String key) {
int index = 0;
int fromIndex = 0;
int result = 0;
if (inputString == null || key == null) {
return 0;
}
while ((index = inputString.indexOf(key, fromIndex)) != -1) {
result++;
fromIndex = index + key.length();
}
return result;
}
If you want to use split, and it's not a bad approach really (although it might be for this particular situation), you need to pass -1 as the second argument to split otherwise it removes empty strings.
See http://ideone.com/gaUw5.
It is good to know this about split. Some languages require the -1 and some do not.
The code
class Main {
public static void main(String[] args) {
String line = "A:B:C:D:E:F:G:H:::::" ;
int delimiterCount = 12 ;
String[] values = line.split(":", -1);
if (values.length != delimiterCount + 1) {
System.out.println("Invalid Line");
} else {
System.out.println("Valid Line");
}
}
}
It should be
String strLine = "A:B:C:D:E:F:G:H: : : : : " ;
int delimiterCount = 12 ;
String[] ValuesArray = strLine.split(":");
if((ValuesArray.length - 1) != delimiterCounter){
System.out.println(Invalid);
}else {
System.out.println("ValidLine");
}
as array will have values not delimeter
No reason to use regex here. If the only criteria for checking the validity of an input is 12 delimeters :, just count them.
String strLine = "A:B:C:D:E:F:G:H:::::";
int EXPECTED_DELIMETERS = 12;
int delimiterCount = 0;
for (int idx = 0; idx < strLine.length(); idx++) {
if (strLine.charAt(idx) == ':') {
delimiterCount++;
}
}
if (EXPECTED_DELIMETERS == delimiterCount) {
System.out.println("ValidLine");
} else {
System.out.println("Invalid");
}
Concise Java 8 solution:
private static boolean isValid(String content, char delimiter, int count) {
return count == content.chars().filter(c -> c == delimiter).count();
}