Replace " in Java String to Get Integer value from it - java

I have a String/Value "2.450,00. I want to get the Integer value from it. For that, I need to remove the " in front of the 2.

First you want to remove the comma sign and the decimals since an int (Integer) is a whole number.
str = str.split(",")[0];
This will split the string on the "," and take the first index which contains the string "2.450". Then you want to remove the punctuation. This can be done by replacing everything which is not a number with an empty space "".
str = str.replaceAll("[^0-9]", "");
Lastly, you want to convert the string to an integer.
int strAsInt = Integer.parseInt(str);
Full code:
public static void main(String[] args) {
// The initial value
String str = "2.450,00";
str = str.split(",")[0];
str = str.replaceAll("[^0-9]", "");
int strAsInt = Integer.parseInt(str);
// This will print the integer value 2450
System.out.println(strAsInt);
}
One liner:
int stringAsInt = Integer.parseInt(str.split(",")[0].replaceAll("[^0-9]", ""));

Try the below snippet. Use substring method to remove "
public static void main(String[] args) {
String str = "\"2.450,00";
// prints the substring after index 1 till str length
String substr = str.substring(1);
System.out.println("substring = " + substr);
}

At first, you need to remove any non-digit character (excluding the '.' and ',' characters) from the input string, the regex "[^\\d\\,\\.]" may help you with this:
final String inputString = "Total: 100.000,05$";
final String numberString = inputString.replaceAll("[^\\d\\,\\.]", "");
The next step is a formatting digit string into a valid double form. At this step, you'll need to replace '.' with an empty string and the ',' with a dot '.'.
final String formattedNumberString = numberString
.replace(".","")
.replace(',', '.');
And, in the end, you are finally able to parse a valid number:
double inputNumber = Double.parseDouble(formattedNumberString);

(1) Remove double quote from string
String str = "\"2.450,00";
str = str.replace("\"", "")
(2) then you should replace the comma as well
str = str.replace(",", "")
(3) Finally you should use the
Integer.parseInt() method to convert String to Integer
int i = Integer.parseInt(str);

Related

How to get rid of white space in palindrome (Java)

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, ""));

Splitting an input currency into a string and an int

In a program where currency is input in the form £2 or 10p, for example, is there a method to split this into two variables in the form
currencyType = £
currencyValue = 2
or
currencyType = p
currencyValue = 10
where currencyType is a string and currencyValue is an int?
An idea for a solution without regular expressions, although I'd prefer one of those:
String entry = "€2.73";
StringBuilder currency = new StringBuilder();
StringBuilder value = new StringBuilder();
for (char c : entry.toCharArray()) {
if (Character.isDigit(c) || c == '.' || c == ',') {
value.append(c);
} else {
currency.append(c);
}
}
System.out.println("Value = " + value + " Currency = " + currency);
Use patten and matcher classes like below. \d+ matches one or more digits where \D+ matches one or more non-digit characters.
String s1 = "£2";
Matcher m = Pattern.compile("(\\D+)|(\\d+)").matcher(s1);
while(m.find())
{
if (m.group(1) != null)
System.out.println("Currency Type: " + m.group(1));
if (m.group(2) != null)
System.out.println("Currency Value: " + m.group(2));
}
Output:
Currency Type: £
Currency Value: 2
OR
Use this regex, if you want to deal also with the decimal value.
Pattern.compile("(\\D+)|(\\d+(?:\\.\\d+)?)");
DEMO
You can use this regular expression to get your result: "(.*?)([\\d,]*)(.*?)"
This will split the input into three groups:
1) Leading currency token
2) Value token (can contain a ',', in the string version you can replaceAll ',' with '' and then convert to integer)
3) Trailing currency token
By looking at the groups from the regex, you can figure out if the leading or trailing currency is present and then get the value from the second group. You can write the code yourself by looking up usage for java regex.
You can input your value as a string, split it normally with the split function and assign each value to its own string. Then convert the string to an integer.
int currencyValue = Integer.parseInt(array[0]);
String currencyType = array[1];
array[] is the array that you split the string into.
String input = user_input.nextLine();
char[] array = input.toCharArray();
for(int i = 0; i < input.length(); i++) {
if (Character.isLetter(array[i])){
//use .split based on the output of the if statement
}
}

Search for particular character inside a string

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');

move first word to the end of the sentence?

Here is SS of the whole question. http://prntscr.com/1dkn2e
it should work with any sentence not just the one given in the example
I know it has to do something with strings. Our professor has gone over with these string methods
http://prntscr.com/1dknco
This is only a basic java class so don't use any complicated stuff
here is what I have, don't know what to do after this
any help would be appreciated.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text. No punctuaton please");
String sentence = keyboard.nextLine();
System.out.println(sentence);
}
}
You can use public String[] split(String regex):
splitted = sentence.split("\\s+");
splitted[0] Is the first word.
splitted[splitted.length - 1] Is the last word.
Since your'e not allowed to use String#split, you can do this trick:
myString = myString.substring(0, myString.lastIndexOf(" ")) + firstWord;
By doing this, you'll have a substring which contains the sentence without the last word. (For extracting the first word, you can use String#indexOf.
firstWord is the first word you extracted before (I'll not solve the whole problem for you, try to do it by yourself, it should be easy now)
Well as it seem your looking for very simple string arithmetic.
So that's the simplest i could do:
// get the index of the start of the second word
int index = line.indexOf (' ');
// get the first char of the second word
char c = line.charAt(index+1);
/* this is a bit ugly, yet necessary in order to convert the
* first char to upper case */
String start = String.valueOf(c).toUpperCase();
// adding the rest of the sentence
start += line.substring (index+2);
// adding space to this string because we cut it
start += " ";
// getting the first word of the setence
String end = line.substring (0 , index);
// print the string
System.out.println(start + end);
try this
String str = "Java is the language";
String first = str.split(" ")[0];
str = str.replace(first, "").trim();
str = str + " " + first;
System.out.println(str);
Here is Another way you can do this.
UPDATED: Without Loops
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text. No punctuaton please");
String sentence = keyboard.nextLine();
System.out.println(sentence);
int spacePosition = sentence.indexOf(" ");
String firstString = sentence.substring(0, spacePosition).trim();
String restOfSentence = sentence.substring(spacePosition, sentence.length()).trim();
String firstChar = restOfSentence.substring(0, 1);
firstChar = firstChar.toUpperCase();
restOfSentence = firstChar + restOfSentence.substring(1, restOfSentence.length());
System.out.println(restOfSentence + " " + firstString);
keyboard.close();

Replacing a letter in a string with a char

String lower = Name.toLowerCase();
int a = Name.indexOf(" ",0);
String first = lower.substring(0, a);
String last = lower.substring(a+1);
char f = first.charAt(0);
char l = last.charAt(0);
f = Character.toUpperCase(f);
l = Character.toUpperCase(l);
String newname = last +" "+ first;
System.out.println(newname);
i want to take variables F and L and replace the lowercase first letters in last and first so they will be uppercase. How can I do this? i want to just replace the first letter in the last and first name with the char first and last
if you are trying to do what i think you are, you should consider using the apache commons-lang library, then look at:
WordUtils.capitalize
obviously, this is also open source, so for the best solution to your homework i'd take a look at the source code.
However, if i were writing it from scratch (and optimum performance wasn't the goal) here's how i would approach it:
public String capitalize(String input)
{
// 1. split on the negated 'word' matcher (regular expressions)
String[] words = input.toLowerCase().split("\\W");
StringBuffer end = new StringBuffer();
for (String word : words)
{
if (word.length == 0)
continue;
end.append(" ");
end.append(Character.toUpperCase(word.charAt(0)));
end.append(word.substring(1));
}
// delete the first space character
return end.deleteCharAt(0).toString();
}
While there's more efficient ways of doing this, you almost got it. You'd just need to concatenate the uppercase chars with the first and last name, bar the first character.
String newname = "" + l + last.subString(1) + " " + f + first.subString(1);
EDIT:
You could also use a string tokenizer to get the names as in:
StringTokenizer st = new StringTokenizer(Name);
String fullName = "";
String currentName;
while (st.hasMoreTokens()) {
/* add spaces between each name */
if(fullName != "") fullName += " ";
currentName = st.nextToken();
fullName += currentName.substring(0,0).toUpperCase() + currentName.substring(1);
}
String name = "firstname lastname";
//match with letter in beginning or a letter after a space
Matcher matcher = Pattern.compile("^\\w| \\w").matcher(name);
StringBuffer b=new StringBuffer();
while(matcher.find())
matcher.appendReplacement(b,matcher.group().toUpperCase());
matcher.appendTail(b);
name=b.toString();//Modified Name

Categories