I have a text (String) an I need to get only digits from it, i mean if i have the text:
"I'm 53.2 km away", i want to get the "53.2" (not 532 or 53 or 2)
I tried the solution in Extract digits from a string in Java. it returns me "532".
Anyone have an idea for it?
Thanx
You can directly use a Scanner which has a nextDouble() and hasNextDouble() methods as below:
Scanner st = new Scanner("I'm 53.2 km away");
while (!st.hasNextDouble())
{
st.next();
}
double value = st.nextDouble();
System.out.println(value);
Output: 53.2
Here is good regex site with tester:
http://gskinner.com/RegExr/
this works fine \d+\.?\d+
import java.util.regex.*;
class ExtractNumber
{
public static void main(String[] args)
{
String str = "I'm 53.2 km away";
String[] s = str.split(" ");
Pattern p = Pattern.compile("(\\d)+\\.(\\d)+");
double d;
for(int i = 0; i< s.length; i++)
{
Matcher m = p.matcher(s[i]);
if(m.find())
d = Double.parseDouble(m.group());
}
System.out.println(d);
}
}
The best and simple way is to use a regex expression and the replaceAll string method. E.g
String a = "2.56 Kms";
String b = a.replaceAll("\\^[0-9]+(\\.[0-9]{1,4})?$","");
Double c = Double.valueOf(b);
System.out.println(c);
If you know for sure your numbers are "words" (space separated) and don't want to use RegExs, you can just parse them...
String myString = "I'm 53.2 km away";
List<Double> doubles = new ArrayList<Double>();
for (String s : myString.split(" ")) {
try {
doubles.add(Double.valueOf(s));
} catch (NumberFormatException e) {
}
}
I have just made a method getDoubleFromString. I think it isn't best solution but it works good!
public static double getDoubleFromString(String source) {
if (TextUtils.isEmpty(source)) {
return 0;
}
String number = "0";
int length = source.length();
boolean cutNumber = false;
for (int i = 0; i < length; i++) {
char c = source.charAt(i);
if (cutNumber) {
if (Character.isDigit(c) || c == '.' || c == ',') {
c = (c == ',' ? '.' : c);
number += c;
} else {
cutNumber = false;
break;
}
} else {
if (Character.isDigit(c)) {
cutNumber = true;
number += c;
}
}
}
return Double.parseDouble(number);
}
Related
It is necessary to repeat the character, as many times as the number behind it.
They are positive integer numbers.
case #1
input: "abc3leson11"
output: "abccclesonnnnnnnnnnn"
I already finish it in the following way:
String a = "abbc2kd3ijkl40ggg2H5uu";
String s = a + "*";
String numS = "";
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
numS = numS + ch;
cnt++;
} else {
cnt++;
try {
for (int j = 0; j < Integer.parseInt(numS); j++) {
System.out.print(s.charAt(i - cnt));
}
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
} catch (Exception e) {
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
}
cnt = 0;
numS = "";
}
}
But I wonder is there some better solution with less and cleaner code?
Could you take a look below? I'm using a library from StringUtils from Apache Common Utils to repeat character:
public class MicsTest {
public static void main(String[] args) {
String input = "abc3leson11";
String output = input;
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(input);
while (m.find()) {
int number = Integer.valueOf(m.group());
char repeatedChar = input.charAt(m.start()-1);
output = output.replaceFirst(m.group(), StringUtils.repeat(repeatedChar, number));
}
System.out.println(output);
}
}
In case you don't want to use StringUtils. You can use the below custom method to achieve the same effect:
public static String repeat(char c, int times) {
char[] chars = new char[times];
Arrays.fill(chars, c);
return new String(chars);
}
Using java basic string regx should make it more terse as follows:
public class He1 {
private static final Pattern pattern = Pattern.compile("[a-zA-Z]+(\\d+).*");
// match the number between or the last using regx;
public static void main(String... args) {
String s = "abc3leson11";
System.out.println(parse(s));
s = "abbc2kd3ijkl40ggg2H5uu";
System.out.println(parse(s));
}
private static String parse(String s) {
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
int num = Integer.valueOf(matcher.group(1));
char prev = s.charAt(s.indexOf(String.valueOf(num)) - 1);
// locate the char before the number;
String repeated = new String(new char[num-1]).replace('\0', prev);
// since the prev is not deleted, we have to decrement the repeating number by 1;
s = s.replaceFirst(String.valueOf(num), repeated);
matcher = pattern.matcher(s);
}
return s;
}
}
And the output should be:
abccclesonnnnnnnnnnn
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
String g(String a){
String result = "";
String[] array = a.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
//System.out.println(java.util.Arrays.toString(array));
for(int i=0; i<array.length; i++){
String part = array[i];
result += part;
if(++i == array.length){
break;
}
char charToRepeat = part.charAt(part.length() - 1);
result += repeat(charToRepeat+"", new Integer(array[i]) - 1);
}
return result;
}
// In Java 11 this could be removed and replaced with the builtin `str.repeat(amount)`
String repeat(String str, int amount){
return new String(new char[amount]).replace("\0", str);
}
Try it online.
Explanation:
The split will split the letters and numbers:
abbc2kd3ijkl40ggg2H5uu would become ["abbc", "2", "kd", "3", "ijkl", "40", "ggg", "2", "H", "5", "uu"]
We then loop over the parts and add any strings as is to the result.
We then increase i by 1 first and if we're done (after the "uu") in the array above, it will break the loop.
If not the increase of i will put us at a number. So it will repeat the last character of the part x amount of times, where x is the number we found minus 1.
Here is another solution:
String str = "abbc2kd3ijkl40ggg2H5uu";
String[] part = str.split("(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)");
String res = "";
for(int i=0; i < part.length; i++){
if(i%2 == 0){
res = res + part[i];
}else {
res = res + StringUtils.repeat(part[i-1].charAt(part[i-1].length()-1),Integer.parseInt(part[i])-1);
}
}
System.out.println(res);
Yet another solution :
public static String getCustomizedString(String input) {
ArrayList<String > letters = new ArrayList<>(Arrays.asList(input.split("(\\d)")));
letters.removeAll(Arrays.asList(""));
ArrayList<String > digits = new ArrayList<>(Arrays.asList(input.split("(\\D)")));
digits.removeAll(Arrays.asList(""));
for(int i=0; i< digits.size(); i++) {
int iteration = Integer.valueOf(digits.get(i));
String letter = letters.get(i);
char c = letter.charAt(letter.length()-1);
for (int j = 0; j<iteration -1 ; j++) {
letters.set(i,letters.get(i).concat(String.valueOf(c)));
}
}
String finalResult = "";
for (String str : letters) {
finalResult += str;
}
return finalResult;
}
The usage:
public static void main(String[] args) {
String testString1 = "abbc2kd3ijkl40ggg2H5uu";
String testString2 = "abc3leson11";
System.out.println(getCustomizedString(testString1));
System.out.println(getCustomizedString(testString2));
}
And the result:
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
abccclesonnnnnnnnnnn
I am new to java programming. I want to print a string with alternate characters in UpperCase.
String x=jTextField1.getText();
x=x.toLowerCase();
int y=x.length();
for(int i=1;i<=y;i++)
{}
I don't know how to proceed further. I want to do this question with the help of looping and continue function.
Help would be appreciated. Thanks.
#Test
public void alternateUppercase(){
String testString = "This is a !!!!! test - of the emergency? broadcast System.";
char[] arr = testString.toLowerCase().toCharArray();
boolean makeUppercase = true;
for (int i=0; i<arr.length; i++) {
if(makeUppercase && Character.isLetter(arr[i])) {
arr[i] = Character.toUpperCase(arr[i]);
makeUppercase = false;
} else if (!makeUppercase && Character.isLetter(arr[i])) {
makeUppercase = true;
}
}
String convertedString = String.valueOf(arr);
System.out.println(convertedString);
}
First, java indexes start at 0 (not 1). I think you are asking for something as simple as alternating calls to Character.toLowerCase(char) and Character.toUpperCase(char) on the result of modulo (remainder of division) 2.
String x = jTextField1.getText();
for (int i = 0, len = x.length(); i < len; i++) {
char ch = x.charAt(i);
if (i % 2 == 0) {
System.out.print(Character.toLowerCase(ch));
} else {
System.out.print(Character.toUpperCase(ch));
}
}
System.out.println();
Strings start at index 0 and finish at index x.length()-1
To look up a String by index you can use String.charAt(i)
To convert a character to upper case you can do Character.toUpperCase(ch);
I suggest you build a StringBuilder from these characters which you can toString() when you are done.
you can make it using the 65 distnace of lower case and upper case ABCabc from the unicode table like:
String str = "abbfFDdshFSDjdFDSsfsSdoi".toLowerCase();
char c;
boolean state = false;
String newStr = "";
for (int i=0; i<str.length(); i++){
c = str.charAt(o);
if (state){
newStr += c;
}
else {
newStr += c + 65;
}
state = !state;
}
I'm sure there is a slicker way to do this, but this will work for a 2 minute-answer:
public String homeWork(){
String x = "Hello World";
StringBuilder sb = new StringBuilder();
for(int i=0;i<=x.length();i++){
char c = x.charAt(i);
if(i%2==0){
sb.append(String.valueOf(c).toUpperCase());
} else {
sb.append(String.valueOf(c).toLowerCase());
}
}
return sb.toString();
}
To explain i%2==0, if the remainder of i divided by 2 is equal to zero (even numbered) return true
public class PrintingStringInAlternativeCase {
public static void main(String s[])
{
String testString = "TESTSTRING";
String output = "";
for (int i = 0; i < testString.length(); i++) {
if(i%2 == 0)
{
output += Character.toUpperCase(testString.toCharArray()[i]);
}else
{
output += Character.toLowerCase(testString.toCharArray()[i]);
}
}
System.out.println("Newly generated string is as follow: "+ output);
}
}
Using as much of your code as I could, here's what I got. First I made a string called build that will help you build your resulting string. Also, I changed the index to go from [0,size-1] not [1,size]. Using modulo devision of 2 helps with the "every other" bit.
String build =""
String x=jTextField1.getText();
x=x.toLowerCase();
int y=x.length();
for(int i=0;i<y;i++)
{
if(i%2==0){
build+=Character.toUpperCase(x.charAt(i));
else{
build+=x.charAt(i);
}
}
x=build; //not necessary, you could just use build.
Happy oding! Leave a comment if you have any questions.
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Stirng");
String str=sc.nextLine();
for(int i=0;i<str.length();i++)
{
if(i%2==0)
{
System.out.print(Character.toLowerCase(str.charAt(i)));
}
else
{
System.out.print(Character.toUpperCase(str.charAt(i)));
}
}
sc.close();
}
Java 8 Solution:
static String getMixedCase(String str) {
char[] chars = str.toCharArray();
return IntStream.range(0, str.length())
.mapToObj(i -> String.valueOf(i % 2 == 1 ? chars[i] : Character.toUpperCase(chars[i])))
.collect(Collectors.joining());
}
public class ClassC {
public static void main(String[] args) {
String str = "Hello";
StringBuffer strNew = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if (i % 2 == 0) {
strNew.append(Character.toLowerCase(str.charAt(i)));
} else {
strNew.append(Character.toUpperCase(str.charAt(i)));
}
}
System.out.println(strNew);
}
}
I've been trying to use an array but it just seems to return the original String.
public static String capitalizeEveryOtherWord(String x) {
x = x.toLowerCase();
x.trim();
String[] words = x.split(" ");
for(int c = 2; c < words.length; c += 2)
words[c].toUpperCase();
return Arrays.toString(words);
}
Could anyone help?
toUpperCase() and trim() return new strings instead of modifying existing ones. You need to assign those new strings to something.
public static String capitalizeEveryOtherWord(String x) {
x = x.toLowerCase();
x = x.trim();
String[] words = x.split(" ");
for (int c = 2; c < words.length; c += 2)
words[c] = words[c].toUpperCase();
return Arrays.toString(words);
}
Also, you probably meant to start at index 0 or 1 – the first or second element, respectively.
Minitech has correctly identified the problem IMHO, but I would use a different regex-based approach:
public static String capitalizeEveryOtherWord(String x) {
StringBuilder result = new StringBuilder(x);
Matcher matcher = Pattern.compile("^ *\\w|\\w* \\w+ \\w").matcher(x);
while(matcher.find())
result.setCharAt(matcher.end() - 1, Character.toUpperCase(x.charAt(matcher.end() - 1)));
return result.toString();
}
(Tested and works).
This also works:
public class answerForStackOverflow {
public static void main(String[] args) {
String examplestring = "iwouldreallyliketothankforallthehelponstackoverflow";
String output = "";
for (int i = 0; i < examplestring.length(); i++) {
char c = examplestring.charAt(i);
if (i % 2 == 0) {
output += examplestring.substring(i, i + 1).toUpperCase();
} else {
output += examplestring.substring(i, i + 1);
}
}
System.out.println(output);
}
}
I have :
String word = "It cost me 500 box
What I want to do is to display this sentence like this :
It cost me
500 box
I need a general methode, not only for this example.
Can you helpe me please ?
As suggested you can use regular expression to do this job below is a code snippet that can do the trick for you:
String word = "It cost me 500 box";
Pattern p = Pattern.compile("(.* )([0-9].*)");
Matcher m = p.matcher(word);
if(m.matches()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
}
Hope this helps.
Not the optimum way but an easy one:
On top of your Activity:
String finalText="";
public static boolean isNumber(String string)
{
try
{
double d = Double.parseDouble(string);
}
catch(NumberFormatException e)
{
return false;
}
return true;
}
In your code:
String word = "It cost me 500 box";
for (int i=0 ; i<word.length() ; i++){
String a = Character.toString(word.charAt(i));
if (isNumber(a)){
finalText+="\n";
for (int j=i ; j<word.length() ; j++){
String b = Character.toString(word.charAt(j));
finalText+=b;
}
i = word.length();
}
else{
finalText+=a;
}
}
textView.setText(finalText);
I don't know if there are anymore inbuilt functions that I know of, but one way of doing this would be:
void match(String string) {
int numIndex = -1;
int charIndex = 0;
if (string.length() > 0) {
while (numIndex == -1 && charIndex < string.length()) {
if (Character.isDigit(string.charAt(charIndex)))
numIndex = charIndex;
charIndex++;
}
}
if (numIndex != -1) {
System.out.println(string.substring(0, numIndex));
System.out.println(string.substring(numIndex));
}
}
How can I extract only the numeric values from the input string?
For example, the input string may be like this:
String str="abc d 1234567890pqr 54897";
I want the numeric values only i.e, "1234567890" and "54897". All the alphabetic and special characters will be discarded.
You could use the .nextInt() method from the Scanner class:
Scans the next token of the input as an int.
Alternatively, you could also do something like so:
String str=" abc d 1234567890pqr 54897";
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(str);
while(m.find())
{
System.out.println(m.group(1));
}
String str=" abc d 1234567890pqr 54897";
Pattern pattern = Pattern.compile("\\w+([0-9]+)\\w+([0-9]+)");
Matcher matcher = pattern.matcher(str);
for(int i = 0 ; i < matcher.groupCount(); i++) {
matcher.find();
System.out.println(matcher.group());
}
Split your string into char array using yourString.toCharArray(); Then iterate through the characters and use Character.isDigit(ch); to identify if this is the numeric value. Or iterate through whole string and use str.charAt(i). For e.g:
public static void main(String[] args) {
String str = "abc d 1234567890pqr 54897";
StringBuilder myNumbers = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
myNumbers.append(str.charAt(i));
System.out.println(str.charAt(i) + " is a digit.");
} else {
System.out.println(str.charAt(i) + " not a digit.");
}
}
System.out.println("Your numbers: " + myNumbers.toString());
}
You could do something like:
Matcher m = Pattern.compile("\\d+").matcher(str);
while (m.find()) {
System.out.println(m.group(0));
}
You can use str = str.replaceAll("replaced_string","replacing_string");
String str=" abc d 1234567890pqr 54897";
String str_rep1=" abc d ";
String str_rep2="pqr ";
String result1=str.replaceAll("", str_rep1);
String result2=str.replaceAll(",",str_rep2);
also what npinti suggests is fine to work with.
Example using java Scanner class
import java.util.Scanner;
Scanner s = new Scanner( "abc d 1234567890pqr 54897" );
s.useDelimiter( "\\D+" );
while ( s.hasNextInt() ){
s.nextInt(); // get int
}
If you do not want to use regex,
String str = " abc d 1234567890pqr 54897";
char[] chars = new char[str.length()];
int i = 0;
for (int j = 0; j < str.length(); j++) {
char c = str.charAt(j);
if (Character.isDigit(c)) {
chars[i++] = c;
if (j != chars.length - 1)
continue;
}
if (chars[0] == '\0')
continue;
String num = new String(chars).trim();
System.out.println(num);
chars = new char[str.length()];
i = 0;
}
Output :
1234567890
54897
String line = "This order was32354 placed 343434for 43411 QT ! OK?";
String regex = "[^\\d]+";
String[] str = line.split(regex);
String required = "";
for(String st: str){
System.out.println(st);
}
By above code you will get all the numeric values. then you can merge them or what ever you wanted to do with those numeric values.
You want to discard everything except digits and spaces:
String nums = input.replaceAll("[^0-9 ]", "").replaceAll(" +", " ").trim();
The extra calls clean up doubled and leading/trailing spaces.
If you need an array, add a split:
String[] nums = input.replaceAll("[^0-9 ]", "").trim().split(" +");
You could split the string on spaces to get the individual entries, loop across them, and try to parse them with the relevant method on Integer, using a try/catch approach to handle the cases where parsing it is as a number fails. That is probably the most straight-forward approach.
Alternatively, you can construct a regex to match only the numbers and use that to find them all. This is probably far more performant for a big string. The regex will look something like `\b\d+\b'.
UPDATE: Or, if this isn't homework or similar (I sort of assumed you were looking for clues to implementing it yourself, but that might not have been valid), you could use the solution that #npinti gives. That's probably the approach you should take in production code.
public static List<String> extractNumbers(String string) {
List<String> numbers = new LinkedList<String>();
char[] array = string.toCharArray();
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < array.length; i++) {
if (Character.isDigit(array[i])) {
stack.push(array[i]);
} else if (!stack.isEmpty()) {
String number = getStackContent(stack);
stack.clear();
numbers.add(number);
}
}
if(!stack.isEmpty()){
String number = getStackContent(stack);
numbers.add(number);
}
return numbers;
}
private static String getStackContent(Stack<Character> stack) {
StringBuilder sb = new StringBuilder();
Enumeration<Character> elements = stack.elements();
while (elements.hasMoreElements()) {
sb.append(elements.nextElement());
}
return sb.toString();
}
public static void main(String[] args) {
String str = " abc d 1234567890pqr 54897";
List<String> extractNumbers = extractNumbers(str);
for (String number : extractNumbers) {
System.out.println(number);
}
}
Just extract the digits
String str=" abc d 1234567890pqr 54897";
for(int i=0; i<str.length(); i++)
if( str.charAt(i) > 47 && str.charAt(i) < 58)
System.out.print(str.charAt(i));
Another version
String str=" abc d 1234567890pqr 54897";
boolean flag = false;
for(int i=0; i<str.length(); i++)
if( str.charAt(i) > 47 && str.charAt(i) < 58) {
System.out.print(str.charAt(i));
flag = true;
} else {
System.out.print( flag ? '\n' : "");
flag = false;
}
public class ExtractNum
{
public static void main(String args[])
{
String input = "abc d 1234567890pqr 54897";
String digits = input.replaceAll("[^0-9.]","");
System.out.println("\nGiven Number is :"+digits);
}
}
public static String convertBudgetStringToPriceInteger(String budget) {
if (!AndroidUtils.isEmpty(budget) && !"0".equalsIgnoreCase(budget)) {
double numbers = getNumericFromString(budget);
if( budget.contains("Crore") ){
numbers= numbers* 10000000;
}else if(budget.contains("Lac")){
numbers= numbers* 100000;
}
return removeTrailingZeroesFromDouble(numbers);
}else{
return "0";
}
}
Get numeric value from alphanumeric string
public static double getNumericFromString(String string){
try {
if(!AndroidUtils.isEmpty(string)){
String commaRemovedString = string.replaceAll(",","");
return Double.parseDouble(commaRemovedString.replaceAll("[A-z]+$", ""));
/*return Double.parseDouble(string.replaceAll("[^[0-9]+[.[0-9]]*]", "").trim());*/
}
}catch (NumberFormatException e){
e.printStackTrace();
}
return 0;
}
For eg . If i pass 1.5 lac or 15,0000 or 15 Crores then we can get numeric value from these fucntion . We can customize string according to our needs.
For eg. Result would be 150000 in case of 1.5 Lac
String str = "abc d 1234567890pqr 54897";
str = str.replaceAll("[^\\d ]", "");
The result will be "1234567890 54897".
String str = "abc34bfg 56tyu";
str = str.replaceAll("[^0-9]","");
output: 3456