I am currently doing an assignment for class and I would like to know how to find an integer inside a string input. So far in the code I have created a way to exit the loop. Please don't give me code just give me some ideas. Keep in mind that I am quite new to java so please bear with me. Thanks.
EDIT: I forgot to mention that the string input should be like "woah123" and it should find only the "123" portion. Sorry
import java.util.Scanner;
public class DoubleTheInt
{
public static void main(String[] args)
{
int EXIT = 0;
while(EXIT == 0)
{
Scanner kbReader = new Scanner(System.in);
System.out.println("What is your sentence?");
String sentence = kbReader.next();
if(sentence.equalsIgnoreCase("exit"))
{
break;
}
}
}
}
For learning purpose what you can do is traverse the whole string and check only for the digits. In this case you will also learn how to check char-by-char in a string if in future you may require this also you will get the digits of that string. Hope that solves your problem.
Here's what you do...
Replace all non numeric characters with empty string using \\D and String.replaceAll function
Parse your string (after replacing) as integer using Integer.parseInt()
Edited after Christian's comment :
replaceAll() function replaces occurances of particular String (Regex is first argument) with that of the second argument String..
\\D is used to select everything except the numbers in the String. So, the above 2 lines combined will give "1234" if your String is "asas1234" .
Now , Integer.parseInt is used to convert a String to integer.. It takes a String as argument and returns an Integer.
Since you are not asking for code , I am giving you some suggestions.
Use regex in string method to find the numbers and to remove all the
non numbers.
Parse the string to integer.
Unless your assignment "is" a regex assignment, I suggest you do it the non-regex way. i.e, by reading character by character and checking for integers or reading the string and converting to a char array and process.
I'm not sure what your teacher intends you to do, but there are two ways-
Read character by character and filter the numbers by their ASCII code. Use BuffferedReader to read from standard input. And use read() method. Figure out the ASCII code range for numbers by experimenting.
Read the entire String at once(using either Scanner or BufferedReader) and see what you can do from the String API(as in the methods available for String).
Use Regular Expression : \d+
String value = "abc123";
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(value);
int i = Integer.valueOf(m.group(1));
System.out.println(i);
output
123
Related
Example:
String t;
String j ="j2se";
Scanner sc =new Scanner(System.in);
System.out.println("enter the search key:");
t=sc.next();
if (j.contains(t))
{
System.out.println("yes");
}
else System.out.println("no");
If the user enters 'j2', 'se' or 'j2s' as an input the output is 'yes'. If the input is 'jse' the output is 'no'.
Is there a method to ignore the number stored in string search like ignoring upper or lower case letters?
Why you don't juste create a copy of this string with no numeric inside ?
And after juste compare this new string with your array ?
Like :
String stringWithoutNumber = j.replaceAll("\\d+","");
stringWithoutNumber.contains(t);
Many of programs have a function called sanitize which clean the url or string before the comparaison.
Hope it's help
-- EDIT --
You don't need to put the + in \\d+ because the method replaceAll replace all the digit. But it's more efficient because it makes less replacement.
use replaceAll("\\d+","") on the String and then compare.
This removes all the numbers from your String. Now you could use this new String and compare.
or use :
\\W+ // replaces everything apart from characters .
I am trying to implement substring replacement, but I am not getting the desired results. Can someone comment on what I may missing here?
public class SubtringReplacement {
public static void main (String[] args){
String input = "xPIy";
if (input.contains("PI") || input.contains("pi") || input.contains("Pi")){
input.replace("PI", "3.14");
}
System.out.println(input);
}
}
Strings are immutable!!
input = input.replace("PI", "3.14");
One problem is that you need to capture the return value when you do the replacement. The other problem is that you will only replace upper case "PI", while it seems you want to replace mixed case instances. Try this instead:
input = input.replaceAll("(PI|pi|Pi)", "3.14");
replace looks for a literal match; replaceAll does a regular expression match, which is what you need.
By the way, you don't need the if condition -- if there is no match, there will be no replacement.
P.S. Look at the comment by #NullUserException if you also want to replace instances of "pI".
Obviously you were missing the Left hand assignment to make your code working with given conditions.
input.replace("PI", "3.14");
But it will only replace, if input contains PI while it will attempt for pi and Pi as well. To better handle this, I think you can use "[pP][iI]" or "[pP]{1}[iI]{1}" as replacement pattern, which will look for one occurrence of P or p followed by one occurrence of I or i e.g. below:
String input = "xPIyPizpIapib";
input = input.replaceAll("[pP][iI]", "3.14");
System.out.println(input); //<- all "pi"s irrespective of case are replaced.
String input = "xPIyPizpIapib";
input = input.replaceAll("[pP]{1}[iI]{1}", "3.14");
System.out.println(input); //<- all "pi"s irrespective of case are replaced.
Please Note: This will also replace pI as wel, if found.
I have this piece of code in my java class
mystring = mysuperstring.split("/");
I want to know how many sub-string is created from the split.
In normal situation, if i want to access the first sub-string i just write
mystring[0];
Also, i want to know if mystring[5] exist or not.
I want to know how many sub-string is created from the split.
Since mystring is an array, you can simply use mystring.length to get the number of substrings.
Also, i want to know if mystring[5] exist or not.
To do this:
if (mystring.length >= 6) { ... }
mystring = mysuperstring.split("/");
int size = mystring.length;
remember that arrays are zero indexed, so where length = 5, the last element will be indexed with 4.
It's a simple way to count the sub-strings
word.split('/').length;
You can see an example of this implementation here.
Try this one & tell me if it works.
import java.util.regex.Pattern;
public class CountSubstring {
public static int countSubstring(String subStr, String str){
// the result of split() will contain one more element than the delimiter
// the "-1" second argument makes it not discard trailing empty strings
return str.split(Pattern.quote(subStr), -1).length - 1;
}
public static void main(String[] args){
System.out.println(countSubstring("th", "the three truths"));
System.out.println(countSubstring("abab", "ababababab"));
System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
}
}
I think you must read about split and array, please find the links.
if you read about split function it returns Array of String.
and now you should read about Array and its size
I wanted to demo a dumy token validation. So I tried to split by dot (.). It did not worked. So, I wonder and checked out an hour with no luck. After a while, when randomly trying I added escape character before dot and thank god it worked :D.
The reason is split takes string as regex. I checked why when writing an answer here:
You are splitting on the regex ., which means "any character"
int len = accessToken.split("\\.").length;
String I wanted to check
String accessToken = Bearer 1111.1111.11111 // demonstration purpose dumy
Output:
3
I have never done regex before, and I have seen they are very useful for working with strings. I saw a few tutorials (for example) but I still cannot understand how to make a simple Java regex check for hexadecimal characters in a string.
The user will input in the text box something like: 0123456789ABCDEF and I would like to know that the input was correct otherwise if something like XTYSPG456789ABCDEF when return false.
Is it possible to do that with a regex or did I misunderstand how they work?
Yes, you can do that with a regular expression:
^[0-9A-F]+$
Explanation:
^ Start of line.
[0-9A-F] Character class: Any character in 0 to 9, or in A to F.
+ Quantifier: One or more of the above.
$ End of line.
To use this regular expression in Java you can for example call the matches method on a String:
boolean isHex = s.matches("[0-9A-F]+");
Note that matches finds only an exact match so you don't need the start and end of line anchors in this case. See it working online: ideone
You may also want to allow both upper and lowercase A-F, in which case you can use this regular expression:
^[0-9A-Fa-f]+$
May be you want to use the POSIX character class \p{XDigit}, so:
^\p{XDigit}+$
Additionally, if you plan to use the regular expression very often, it is recommended to use a constant in order to avoid recompile it each time, e.g.:
private static final Pattern REGEX_PATTERN =
Pattern.compile("^\\p{XDigit}+$");
public static void main(String[] args) {
String input = "0123456789ABCDEF";
System.out.println(
REGEX_PATTERN.matcher(input).matches()
); // prints "true"
}
Actually, the given answer is not totally correct. The problem arises because the numbers 0-9 are also decimal values. PART of what you have to do is to test for 00-99 instead of just 0-9 to ensure that the lower values are not decimal numbers. Like so:
^([0-9A-Fa-f]{2})+$
To say these have to come in pairs! Otherwise - the string is something else! :-)
Example:
(Pick one)
var a = "1e5";
var a = "10";
var a = "314159265";
If I used the accepted answer in a regular expression it would return TRUE.
var re1 = new RegExp( /^[0-9A-Fa-f]+$/ );
var re2 = new RegExp( /^([0-9A-Fa-f]{2})+$/ );
if( re1.test(a) ){ alert("#1 = This is a hex value!"); }
if( re2.test(a) ){ alert("#2 = This IS a hex string!"); }
else { alert("#2 = This is NOT a hex string!"); }
Note that the "10" returns TRUE in both cases. If an incoming string only has 0-9 you can NOT tell, easily if it is a hex value or a decimal value UNLESS there is a missing zero in front of off length strings (hex values always come in pairs - ie - Low byte/high byte). But values like "34" are both perfectly valid decimal OR hexadecimal numbers. They just mean two different things.
Also note that "3.14159265" is not a hex value no matter which test you do because of the period. But with the addition of the "{2}" you at least ensure it really is a hex string rather than something that LOOKS like a hex string.
I have a string which contains alphanumeric character.
I need to check whether the string is started with number.
Thanks,
See the isDigit(char ch) method:
https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Character.html
and pass it to the first character of the String using the String.charAt() method.
Character.isDigit(myString.charAt(0));
Sorry I didn't see your Java tag, was reading question only. I'll leave my other answers here anyway since I've typed them out.
Java
String myString = "9Hello World!";
if ( Character.isDigit(myString.charAt(0)) )
{
System.out.println("String begins with a digit");
}
C++:
string myString = "2Hello World!";
if (isdigit( myString[0]) )
{
printf("String begins with a digit");
}
Regular expression:
\b[0-9]
Some proof my regex works: Unless my test data is wrong?
I think you ought to use a regex:
import java.util.regex.*;
public class Test {
public static void main(String[] args) {
String neg = "-123abc";
String pos = "123abc";
String non = "abc123";
/* I'm not sure if this regex is too verbose, but it should be
* clear. It checks that the string starts with either a series
* of one or more digits... OR a negative sign followed by 1 or
* more digits. Anything can follow the digits. Update as you need
* for things that should not follow the digits or for floating
* point numbers.
*/
Pattern pattern = Pattern.compile("^(\\d+.*|-\\d+.*)");
Matcher matcher = pattern.matcher(neg);
if(matcher.matches()) {
System.out.println("matches negative number");
}
matcher = pattern.matcher(pos);
if (matcher.matches()) {
System.out.println("positive matches");
}
matcher = pattern.matcher(non);
if (!matcher.matches()) {
System.out.println("letters don't match :-)!!!");
}
}
}
You may want to adjust this to accept floating point numbers, but this will work for negatives. Other answers won't work for negatives because they only check the first character! Be more specific about your needs and I can help you adjust this approach.
This should work:
String s = "123foo";
Character.isDigit(s.charAt(0));
System.out.println(Character.isDigit(mystring.charAt(0));
EDIT: I searched for java docs, looked at methods on string class which can get me 1st character & looked at methods on Character class to see if it has any method to check such a thing.
I think, you could do the same before asking it.
EDI2: What I mean is, try to do things, read/find & if you can't find anything - ask.
I made a mistake when posting it for the first time. isDigit is a static method on Character class.
Use a regex like ^\d