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
Related
I want to remove words from an input string that contain more vowels than consonants.
I wish to use a regular expression for this, can anyone give me any advice?
Input: eef geggughhht oaiu hjekloykj
Output: geggughhht hjekloykj
here's some my pseudo code
String str = "eef geggughhht oaiu hjekloykj";
Pattern pattern = Pattern.compile("[aeiou]+");
for (String ch : str.split(" ")) {
Matcher matcher = pattern.matcher(ch);
int countVowels = 0;
int countConsonants = 0;
for(int i = 0; i < ch.length(); i++) {
if(matcher.find(i)){
countVowels++;
} else {
countConsonants++;
}
}
if (countVowels > countConsonants){
System.out.println();
} else {
System.out.println(ch);
}
}
You may use this approach:
String str = "eef geggughhht oaiu hjekloykj";
final Pattern p = Pattern.compile("[aeiou]+", Pattern.CASE_INSENSITIVE);
String[] arr = str.split("\\s+");
for (int i=0; i<arr.length; i++) {
String cstr = p.matcher(arr[i]).replaceAll("");
if ( cstr.length() >= (arr[i].length() - cstr.length()) ) {
System.out.println(arr[i]);
}
}
Output:
geggughhht
hjekloykj
Using this approach we remove all vowels in each word of the string and then compare remaining string's (com[rising all consonants) length with vowel's string.
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);
}
So say I have a string called x that = "Hello world". I want to somehow make it so that it will flip those two words and instead display "world Hello". I am not very good with loops or arrays and obviously am a beginner. Could I accomplish this somehow by splitting my string? If so, how? If not, how could I do this? Help would be appreciated, thanks!
1) split string into String array on space.
String myArray[] = x.split(" ");
2) Create new string with words in reverse order from array.
String newString = myArray[1] + " " + myArray[0];
Bonus points for using a StringBuilder instead of concatenation.
String abc = "Hello world";
String cba = abc.replace( "Hello world", "world Hello" );
abc = "This is a longer string. Hello world. My String";
cba = abc.replace( "Hello world", "world Hello" );
If you want, you can explode your string as well:
String[] pieces = abc.split(" ");
for( int i=0; i<pieces.length-1; ++i )
if( pieces[i]=="Hello" && pieces[i+1]=="world" ) swap(pieces[i], pieces[i+1]);
There are many other ways you can do it too. Be careful for capitalization. You can use .toUpperCase() in your if statements and then make your matching conditionals uppercase, but leave the results with their original capitalization, etc.
Here's the solution:
import java.util.*;
public class ReverseWords {
public String reverseWords(String phrase) {
List<String> wordList = Arrays.asList(phrase.split("[ ]"));
Collections.reverse(wordList);
StringBuilder sbReverseString = new StringBuilder();
for(String word: wordList) {
sbReverseString.append(word + " ");
}
return sbReverseString.substring(0, sbReverseString.length() - 1);
}
}
The above solution was coded by me, for Google Code Jam and is also blogged here: Reverse Words - GCJ 2010
Just use this method, call it and pass the string that you want to split out
static String reverseWords(String str) {
// Specifying the pattern to be searched
Pattern pattern = Pattern.compile("\\s");
// splitting String str with a pattern
// (i.e )splitting the string whenever their
// is whitespace and store in temp array.
String[] temp = pattern.split(str);
String result = "";
// Iterate over the temp array and store
// the string in reverse order.
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1) {
result = temp[i] + result;
} else {
result = " " + temp[i] + result;
}
}
return result;
}
Depending on your exact requirements, you may want to split on other forms of whitespace (tabs, multiple spaces, etc.):
static Pattern p = Pattern.compile("(\\S+)(\\s+)(\\S+)");
public String flipWords(String in)
{
Matcher m = p.matcher(in);
if (m.matches()) {
// reverse the groups we found
return m.group(3) + m.group(2) + m.group(1);
} else {
return in;
}
}
If you want to get more complex see the docs for Pattern http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
Try something as follows:
String input = "how is this";
List<String> words = Arrays.asList(input.split(" "));
Collections.reverse(words);
String result = "";
for(String word : words) {
if(!result.isEmpty()) {
result += " ";
}
result += word;
}
System.out.println(result);
Output:
this is how
Too much?
private static final Pattern WORD = Pattern.compile("^(\\p{L}+)");
private static final Pattern NUMBER = Pattern.compile("^(\\p{N}+)");
private static final Pattern SPACE = Pattern.compile("^(\\p{Z}+)");
public static String reverseWords(final String text) {
final StringBuilder sb = new StringBuilder(text.length());
final Matcher wordMatcher = WORD.matcher(text);
final Matcher numberMatcher = NUMBER.matcher(text);
final Matcher spaceMatcher = SPACE.matcher(text);
int offset = 0;
while (offset < text.length()) {
wordMatcher.region(offset, text.length());
numberMatcher.region(offset, text.length());
spaceMatcher.region(offset, text.length());
if (wordMatcher.find()) {
final String word = wordMatcher.group();
sb.insert(0, reverseCamelCase(word));
offset = wordMatcher.end();
} else if (numberMatcher.find()) {
sb.insert(0, numberMatcher.group());
offset = numberMatcher.end();
} else if (spaceMatcher.find()) {
sb.insert(0, spaceMatcher.group(0));
offset = spaceMatcher.end();
} else {
sb.insert(0, text.charAt(offset++));
}
}
return sb.toString();
}
private static final Pattern CASE_REVERSAL = Pattern
.compile("(\\p{Lu})(\\p{Ll}*)(\\p{Ll})$");
private static String reverseCamelCase(final String word) {
final StringBuilder sb = new StringBuilder(word.length());
final Matcher caseReversalMatcher = CASE_REVERSAL.matcher(word);
int wordEndOffset = word.length();
while (wordEndOffset > 0 && caseReversalMatcher.find()) {
sb.insert(0, caseReversalMatcher.group(3).toUpperCase());
sb.insert(0, caseReversalMatcher.group(2));
sb.insert(0, caseReversalMatcher.group(1).toLowerCase());
wordEndOffset = caseReversalMatcher.start();
caseReversalMatcher.region(0, wordEndOffset);
}
sb.insert(0, word.substring(0, wordEndOffset));
return sb.toString();
}
Is it possible to make String.replaceAll put the number (count) of the current replacement into the replacement being made?
So that "qqq".replaceAll("(q)", "something:$1 ") would result in "1:q 2:q 3:q"?
Is there anything that I can replace something in the code above with, to make it resolve into the current substitution count?
Here is one way of doing this:
StringBuffer resultString = new StringBuffer();
String subjectString = new String("qqqq");
Pattern regex = Pattern.compile("q");
Matcher regexMatcher = regex.matcher(subjectString);
int i = 1;
while (regexMatcher.find()) {
regexMatcher.appendReplacement(resultString, i+":"+regexMatcher.group(1)+" ");
i++;
}
regexMatcher.appendTail(resultString);
System.out.println(resultString);
See it
No, not with the replaceAll method. The only backreference is \n where n is the n'th capturing group matched.
For this you have to create your own replaceAll() method.
This helps you:
public class StartTheClass
{
public static void main(String[] args)
{
String string="wwwwww";
System.out.println("Replaced As: \n"+replaceCharector(string, "ali:", 'w'));
}
public static String replaceCharector(String original, String replacedWith, char toReplaceChar)
{
int count=0;
String str = "";
for(int i =0; i < original.length(); i++)
{
if(original.charAt(i) == toReplaceChar)
{
str += replacedWith+(count++)+" ";//here add the 'count' value and some space;
}
else
{
str += original.charAt(i);
}
}
return str;
}
}
The output I got is:
Replaced As:
ali:0 ali:1 ali:2 ali:3 ali:4 ali:5
This question already has answers here:
How to capitalize the first character of each word in a string
(51 answers)
Closed 3 years ago.
I have a string: "hello good old world" and i want to upper case every first letter of every word, not the whole string with .toUpperCase(). Is there an existing java helper which does the job?
Have a look at ACL WordUtils.
WordUtils.capitalize("your string") == "Your String"
Here is the code
String source = "hello good old world";
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print("Result: " + res.toString().trim());
sString = sString.toLowerCase();
sString = Character.toString(sString.charAt(0)).toUpperCase()+sString.substring(1);
i dont know if there is a function but this would do the job in case there is no exsiting one:
String s = "here are a bunch of words";
final StringBuilder result = new StringBuilder(s.length());
String[] words = s.split("\\s");
for(int i=0,l=words.length;i<l;++i) {
if(i>0) result.append(" ");
result.append(Character.toUpperCase(words[i].charAt(0)))
.append(words[i].substring(1));
}
import org.apache.commons.lang.WordUtils;
public class CapitalizeFirstLetterInString {
public static void main(String[] args) {
// only the first letter of each word is capitalized.
String wordStr = WordUtils.capitalize("this is first WORD capital test.");
//Capitalize method capitalizes only first character of a String
System.out.println("wordStr= " + wordStr);
wordStr = WordUtils.capitalizeFully("this is first WORD capital test.");
// This method capitalizes first character of a String and make rest of the characters lowercase
System.out.println("wordStr = " + wordStr );
}
}
Output :
This Is First WORD Capital Test.
This Is First Word Capital Test.
Here's a very simple, compact solution. str contains the variable of whatever you want to do the upper case on.
StringBuilder b = new StringBuilder(str);
int i = 0;
do {
b.replace(i, i + 1, b.substring(i,i + 1).toUpperCase());
i = b.indexOf(" ", i) + 1;
} while (i > 0 && i < b.length());
System.out.println(b.toString());
It's best to work with StringBuilder because String is immutable and it's inefficient to generate new strings for each word.
Trying to be more memory efficient than splitting the string into multiple strings, and using the strategy shown by Darshana Sri Lanka. Also, handles all white space between words, not just the " " character.
public static String UppercaseFirstLetters(String str)
{
boolean prevWasWhiteSp = true;
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (Character.isLetter(chars[i])) {
if (prevWasWhiteSp) {
chars[i] = Character.toUpperCase(chars[i]);
}
prevWasWhiteSp = false;
} else {
prevWasWhiteSp = Character.isWhitespace(chars[i]);
}
}
return new String(chars);
}
String s = "java is an object oriented programming language.";
final StringBuilder result = new StringBuilder(s.length());
String words[] = s.split("\\ "); // space found then split it
for (int i = 0; i < words.length; i++)
{
if (i > 0){
result.append(" ");
}
result.append(Character.toUpperCase(words[i].charAt(0))).append(
words[i].substring(1));
}
System.out.println(result);
Output: Java Is An Object Oriented Programming Language.
Also you can take a look into StringUtils library. It has a bunch of cool stuff.
My code after reading a few above answers.
/**
* Returns the given underscored_word_group as a Human Readable Word Group.
* (Underscores are replaced by spaces and capitalized following words.)
*
* #param pWord
* String to be made more readable
* #return Human-readable string
*/
public static String humanize2(String pWord)
{
StringBuilder sb = new StringBuilder();
String[] words = pWord.replaceAll("_", " ").split("\\s");
for (int i = 0; i < words.length; i++)
{
if (i > 0)
sb.append(" ");
if (words[i].length() > 0)
{
sb.append(Character.toUpperCase(words[i].charAt(0)));
if (words[i].length() > 1)
{
sb.append(words[i].substring(1));
}
}
}
return sb.toString();
}
import java.util.Scanner;
public class CapitolizeOneString {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Please enter Your word = ");
String str=scan.nextLine();
printCapitalized( str );
} // end main()
static void printCapitalized( String str ) {
// Print a copy of str to standard output, with the
// first letter of each word in upper case.
char ch; // One of the characters in str.
char prevCh; // The character that comes before ch in the string.
int i; // A position in str, from 0 to str.length()-1.
prevCh = '.'; // Prime the loop with any non-letter character.
for ( i = 0; i < str.length(); i++ ) {
ch = str.charAt(i);
if ( Character.isLetter(ch) && ! Character.isLetter(prevCh) )
System.out.print( Character.toUpperCase(ch) );
else
System.out.print( ch );
prevCh = ch; // prevCh for next iteration is ch.
}
System.out.println();
}
} // end class
public class WordChangeInCapital{
public static void main(String[] args)
{
String s="this is string example";
System.out.println(s);
//this is input data.
//this example for a string where each word must be started in capital letter
StringBuffer sb=new StringBuffer(s);
int i=0;
do{
b.replace(i,i+1,sb.substring(i,i+1).toUpperCase());
i=b.indexOf(" ",i)+1;
} while(i>0 && i<sb.length());
System.out.println(sb.length());
}
}
package com.raj.samplestring;
/**
* #author gnagara
*/
public class SampleString {
/**
* #param args
*/
public static void main(String[] args) {
String[] stringArray;
String givenString = "ramu is Arr Good boy";
stringArray = givenString.split(" ");
for(int i=0; i<stringArray.length;i++){
if(!Character.isUpperCase(stringArray[i].charAt(0))){
Character c = stringArray[i].charAt(0);
Character change = Character.toUpperCase(c);
StringBuffer ss = new StringBuffer(stringArray[i]);
ss.insert(0, change);
ss.deleteCharAt(1);
stringArray[i]= ss.toString();
}
}
for(String e:stringArray){
System.out.println(e);
}
}
}
Here is an easy solution:
public class CapitalFirstLetters {
public static void main(String[] args) {
String word = "it's java, baby!";
String[] wordSplit;
String wordCapital = "";
wordSplit = word.split(" ");
for (int i = 0; i < wordSplit.length; i++) {
wordCapital = wordSplit[i].substring(0, 1).toUpperCase() + wordSplit[i].substring(1) + " ";
}
System.out.println(wordCapital);
}}
public String UpperCaseWords(String line)
{
line = line.trim().toLowerCase();
String data[] = line.split("\\s");
line = "";
for(int i =0;i< data.length;i++)
{
if(data[i].length()>1)
line = line + data[i].substring(0,1).toUpperCase()+data[i].substring(1)+" ";
else
line = line + data[i].toUpperCase();
}
return line.trim();
}
So much simpler with regexes:
Pattern spaces=Pattern.compile("\\s+[a-z]");
Matcher m=spaces.matcher(word);
StringBuilder capitalWordBuilder=new StringBuilder(word.substring(0,1).toUpperCase());
int prevStart=1;
while(m.find()) {
capitalWordBuilder.append(word.substring(prevStart,m.end()-1));
capitalWordBuilder.append(word.substring(m.end()-1,m.end()).toUpperCase());
prevStart=m.end();
}
capitalWordBuilder.append(word.substring(prevStart,word.length()));
Output for input: "this sentence Has Weird caps"
This Sentence Has Weird Caps