What is the best way to extract the integer part of a string like
Hello123
How do you get the 123 part. You can sort of hack it using Java's Scanner, is there a better way?
As explained before, try using Regular Expressions. This should help out:
String value = "Hello123";
String intValue = value.replaceAll("[^0-9]", ""); // returns 123
And then you just convert that to an int (or Integer) from there.
I believe you can do something like:
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();
EDIT: Added useDelimiter suggestion by Carlos
Why don't you just use a Regular Expression to match the part of the string that you want?
[0-9]
That's all you need, plus whatever surrounding chars it requires.
Look at http://www.regular-expressions.info/tutorial.html to understand how Regular expressions work.
Edit: I'd like to say that Regex may be a little overboard for this example, if indeed the code that the other submitter posted works... but I'd still recommend learning Regex's in general, for they are very powerful, and will come in handy more than I'd like to admit (after waiting several years before giving them a shot).
Assuming you want a trailing digit, this would work:
import java.util.regex.*;
public class Example {
public static void main(String[] args) {
Pattern regex = Pattern.compile("\\D*(\\d*)");
String input = "Hello123";
Matcher matcher = regex.matcher(input);
if (matcher.matches() && matcher.groupCount() == 1) {
String digitStr = matcher.group(1);
Integer digit = Integer.parseInt(digitStr);
System.out.println(digit);
}
System.out.println("done.");
}
}
I had been thinking Michael's regex was the simplest solution possible, but on second thought just "\d+" works if you use Matcher.find() instead of Matcher.matches():
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Example {
public static void main(String[] args) {
String input = "Hello123";
int output = extractInt(input);
System.out.println("input [" + input + "], output [" + output + "]");
}
//
// Parses first group of consecutive digits found into an int.
//
public static int extractInt(String str) {
Matcher matcher = Pattern.compile("\\d+").matcher(str);
if (!matcher.find())
throw new NumberFormatException("For input string [" + str + "]");
return Integer.parseInt(matcher.group());
}
}
Although I know that it's a 6 year old question, but I am posting an answer for those who want to avoid learning regex right now(which you should btw). This approach also gives the number in between the digits(for eg. HP123KT567 will return 123567)
Scanner scan = new Scanner(new InputStreamReader(System.in));
System.out.print("Enter alphaNumeric: ");
String x = scan.next();
String numStr = "";
int num;
for (int i = 0; i < x.length(); i++) {
char charCheck = x.charAt(i);
if(Character.isDigit(charCheck)) {
numStr += charCheck;
}
}
num = Integer.parseInt(numStr);
System.out.println("The extracted number is: " + num);
This worked for me perfectly.
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("string1234more567string890");
while(m.find()) {
System.out.println(m.group());
}
OutPut:
1234
567
890
String[] parts = s.split("\\D+"); //s is string containing integers
int[] a;
a = new int[parts.length];
for(int i=0; i<parts.length; i++){
a[i]= Integer.parseInt(parts[i]);
System.out.println(a[i]);
}
We can simply use regular expression to extract the integer value from string
String str= "HEll1oTe45st23";
String intValue = str.replaceAll("[^0-9]", "");
System.out.print(Integer.parseInt(intValue));
Here, you can replaceAll string values with empty values and then parse the string to integer value. Further, you can use integer values.
Related
public class reverserapp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter a word");
String str = scan.nextLine();
String reverse = "";
for( int i = str.length() - 1; i >= 0; i--)
reverse += str.charAt(i);
if(reverse.equalsIgnoreCase(str))
System.out.println("Palindrome");
else System.out.println("Not Palindrome");
}
}
This is my palindrome code. I'm doing this for a small assignment. I can get single words to work but if I write a something like "Don’t nod" it shows up as not palindrome. How can I achieve this? I'd like for my code to ignore punctuation's and white space.
So in the end result should be like "dontnod"
Thanks in advance for any help, complete noob at this.
Remove all non-letter characters, then put the resulting String to lower case .
str = str.replaceAll("[^a-zA-Z]", "");
str = str.toLowerCase();
You can use the replace function from StringUtils.
Example:
StringUtils.replace("asdasd aaaa", " ", ""); //-> output: asdasdaaaa
You can define a regex to remove punctuation and space, and perform a String replace on input, e.g.:
String regex = "[\\p{Punct}\\s]";
String input = "don't nod";
System.out.println(input.replaceAll(regex, ""));
I have to write a program that takes a user's chemical equation as an input, like NaCl2, and separate it out into individual elements and the number associated with them. Is there a way to parse through a string and pair the individual elements, like in NaCl2 into Na and Cl2?
As you mentioned in a comment, checking whether letters are uppercase or lowercase is key to this problem. What you're looking for to solve this is the Character.isUppercase() method. Your code should iterate over the characters in the input String and pass each to this method. I wrote up this rough draft of a code to demonstrate it (and it also prints the output for you - how convenient!):
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> elements = new ArrayList<>();
System.out.print("Enter formula: ");
String formula = sc.next();
String s = "";
for (int i=0; i<formula.length(); i++) {
if (Character.isUpperCase(formula.charAt(i))) {
if (!s.isEmpty()) {
elements.add(s);
}
s = "" + formula.charAt(i);
} else {
s += formula.charAt(i);
}
}
elements.add(s);
for (int i=0; i<elements.size(); i++) {
System.out.print(elements.get(i) + " ");
}
System.out.println();
}
This can be done a number of ways. One of them is using regular expressions. In this case the expression looks for an uppercase character, followed optionally by a lower case character, followed optionally by a number.
Pattern elementPattern = Pattern.compile("(\\p{Upper}\\p{Lower}?)(\\p{Digit}*)");
This can be used to find all the elements in the input:
Matcher elementMatcher = elementPattern.match(input);
while (elementMatcher.find()) {
String element = elementMatcher.group(1);
String count = elementMatcher.group(2);
System.out.println("Element: " + element + " count: " + count);
}
I have the following code that takes 2 strings as inputs and returns Boolean on whether they're anagrams:
import java.util.ArrayList;
import java.util.Scanner;
public class AnagramChecker {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print ("Enter string 1: ");
String str1 = sc.nextLine();
System.out.print ("Enter string 2: ");
String str2 = sc.nextLine();
boolean check = isAnagram (str1, str2);
System.out.println ("Anagram check for '" + str1 + "' and '" + str2 + "': " + check);
sc.close();
}
public static boolean isAnagram (String s1, String s2) {
if(s1.length() != s2.length())
return false;
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
ArrayList<String> myList = new ArrayList<String>();
for(int i = 0; i < s2.length() ; i++ ){
myList.add(String.valueOf(s2.charAt(i)));
}
for(int i = 0; i < s1.length();i++){
for(int j = 0; j < myList.size(); j++){
if(myList.get(j).equals(String.valueOf(s1.charAt(i)))){
myList.remove(j);
j = 0;
break;
}
}
}
return myList.isEmpty();
}
}
It is somewhat limited though, I'm trying to expand it to work for the following cases:
- different cases i.e. eager == AGREE
- single word with whitespaces i.e. eager == a g ree
- different amounts of whitespace i.e. " eager" == agree
Is there a nice and clean way to integrate this into already written code above without much pain and re-writing. Any help much appreciated. Thanks.
Yes there is. Regex to the rescue! You can use the String built in .replaceAll(). Passing it the \s value will remove all spaces and characters not printed such as \n. I would suggest that during comparison you use something like the following:
string1.replaceAll("\\s","").equals(string2.replaceAll("\\s",""));
personally I would do the following
use trim() to remove leading and traiing whitespace
use replace to remove whitespaces
use toLowerCase() to make the text lower case
convert the Strings into an array list of characters
sort the arrays
compare the arrays - if they are the same then you have an anagram
I have a string .. I need to search for some particular texts inside this string if it is present total numbers need to be returned.
I know how to return a character of particular place
String string = "Hi How are you";
b = string.contains("H") ;
But I need to get multiple characters for example..I need to search for 'A' and 'S' inside a string and I need number of times it is coming.
how I will write the code for that.I know how to search in a particular place and search for a particular character. But how for more than i character and return its total number.
String string = "Hai How are you!";
char aChar = anotherPalindrome.charAt(9);
I know it will reeturn 9th place character.
String string = "Niagara. O roar again!";
String roar = string.substring(5, 7);
I know it will return 'How'
You have to use regular expressions. Android provides the Pattern class to this kind of things.
You can do like this here three characters AJS can be searched.. if you need to search its small characters give like 'AaJaSs'..
String string;
Pattern pattern = Pattern.compile("([AJS])"); //case insensitive
Matcher matcher = pattern.matcher(String);
int count = 0;
while (matcher.find()) count++;
Try looping with help of the indexOf() method.
Example:
String exampleString = "Hai How are you!";
String searchedString = "H";
int index = exampleString.indexOf(searchedString , 0);
int counter = 0;
while(index != -1) {
counter++;
int index = exampleString.indexOf(searchedString , index);
}
System.out.println("The character " + searchedString + " occurs " + counter + " times.");
You can make a method to count the frequency of the character in the string :
public static int count(char character){
return str.toUpperCase().split((""+character).toUpperCase()).length - 1;
}
Then use this method as shown below:
b = string.count('H');
b = string.count('A');
The output is always a String, for example H,E,L,L,O,. How could I limit the commas? I want the commas only between letters, for example H,E,L,L,O.
import java.util.Scanner;
import java.lang.String;
public class forLoop
{
public static void main(String[] args)
{
Scanner Scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String Str1 = Scan.next();
String newString="";
String Str2 ="";
for (int i=0; i < Str1.length(); i++)
{
newString = Str1.charAt(i) + ",";
Str2 = Str2 + newString;
}
System.out.print(Str2);
}
}
Since this is homework I'll help you out a little without giving the answer:
If you want the output to only be inbetween letters IE: A,B,C instead of A,B,C, which is what I imagine you are asking about. Then you need to look at your for loop and check the boundary conditions.
The easiest way I see is :
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String Str1 = Scan.nextLine();
String newString="";
String Str2 ="";
for (int i=0; i < Str1.length()-1; i++)
{
newString = Str1.charAt(i) + ",";
Str2 = Str2 + newString;
}
Str2 = Str2 + Str1.charAt(Str1.length()-1);
System.out.println(Str2);
}
The output it will give is :
run:
Enter a string: Hello world
H,e,l,l,o, ,w,o,r,l,d
BUILD SUCCESSFUL (total time: 5 seconds)
Though I will highly recommend learning regular expression as suggested by #Roman. Till then this will do the trick. :)
Try regular expressions:
String input = scanner.next();
String output = input.replaceAll(".", "$0,");
With spaces it would be a bit easier since you don't need to abandon last 'odd' comma:
output = output.substring (0, ouput.length() - 2);
When you've figured out the loop-solution, you could try the following ;)
System.out.println(Arrays.toString("HELLO".toCharArray()).replaceAll("[\\[ \\]]", ""));
Just don't append the comma when the last item of the loop is to be appended. You have the item index by i and the string length by Str2.length(). Just do the primary school math with a lesser-than or a greater-than operator in an if statement.
The following snippet should be instructive. It shows:
How to use StringBuilder for building strings
How to process each char in a String using an explicit index
How to detect if it's the first/last iteration for special processing
String s = "HELLO";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (i == 0) { // first
sb.append("(" + ch + ")");
} else if (i == s.length() - 1) { // last
sb.append("<" + ch + ">");
} else { // everything in between
sb.append(Character.toLowerCase(ch));
}
}
System.out.println(sb.toString());
// prints "(H)ell<O>"