i have a string that has a int value in it. i just want to extract the int value from the string and print.
String str="No. of Days : 365";
String daysWithSplChar = str.replaceAll("[a-z][A-Z]","").trim();
char[] ch = daysWithSplChar.toCharArray();
StringBuffer stb = new StringBuffer();
for(char c : ch)
{
if(c >= '0' && c <= '9')
{
stb.append(c);
}
}
int days = Integer.ParseInt(stb.toString());
is there any better way than this. please let me know.
try String.replaceAll
String str = "No. of Days : 365";
str = str.replaceAll(".*?(\\d+).*", "$1");
System.out.println(str);
you will get
365
Another way of using regex (other than the way suggested by #EvgeniyDorofeev) which is closer to what you did:
str.replaceAll("[^0-9]",""); // give you "365"
which means, replace everything that is not 0-9 with empty string (or, in another word, remove all non-digit characters)
This is meaning the same, just a matter of taste which one is more comfortable to you:
str.replaceAll("\\D",""); // give you "365"
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();
This will get you the integer
following code gives you integer value
String str = "No. of Days : 365";
str = str.replaceAll(".*?(\\d+)", "$1");
System.out.println(str);
Integer x = Integer.valueOf(str);//365 in integer type
System.out.println(x+1);//output 366
Related
I'm currently trying to loop through a String and identity a specific character within that string then add a specific character following on from the originally identified character.
For example using the string: aaaabbbcbbcbb
And the character I want to identify being: c
So every time a c is detected a following c will be added to the string and the loop will continue.
Thus aaaabbbcbbcbb will become aaaabbbccbbccbb.
I've been trying to make use of indexOf(),substring and charAt() but I'm currently either overriding other characters with a c or only detecting one c.
I know you've asked for a loop, but won't something as simple as a replace suffice?
String inputString = "aaaabbbcbbcbb";
String charToDouble = "c";
String result = inputString.replace(charToDouble, charToDouble+charToDouble);
// or `charToDouble+charToDouble` could be `charToDouble.repeat(2)` in JDK 11+
Try it online.
If you insist on using a loop however:
String inputString = "aaaabbbcbbcbb";
char charToDouble = 'c';
String result = "";
for(char c : inputString.toCharArray()){
result += c;
if(c == charToDouble){
result += c;
}
}
Try it online.
Iterate over all the characters. Add each one to a StringBuilder. If it matches the character you're looking for then add it again.
final String test = "aaaabbbcbbcbb";
final char searchChar = 'c';
final StringBuilder builder = new StringBuilder();
for (final char c : test.toCharArray())
{
builder.append(c);
if (c == searchChar)
{
builder.append(c);
}
}
System.out.println(builder.toString());
Output
aaaabbbccbbccbb
You probably are trying to modify a String in java. Strings in Java are immutable and cannot be changed like one might do in c++.
You can use StringBuilder to insert characters. eg:
StringBuilder builder = new StringBuilder("acb");
builder.insert(1, 'c');
The previous answer suggesting String.replace is the best solution, but if you need to do it some other way (e.g. for an exercise), then here's a 'modern' solution:
public static void main(String[] args) {
final String inputString = "aaaabbbcbbcbb";
final int charToDouble = 'c'; // A Unicode codepoint
final String result = inputString.codePoints()
.flatMap(c -> c == charToDouble ? IntStream.of(c, c) : IntStream.of(c))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
assert result.equals("aaaabbbccbbccbb");
}
This looks at each character in turn (in an IntStream). It doubles the character if it matches the target. It then accumulates each character in a StringBuilder.
A micro-optimization can be made to pre-allocate the StringBuilder's capacity. We know the maximum possible size of the new string is double the old string, so StringBuilder::new can be replaced by () -> new StringBuilder(inputString.length()*2). However, I'm not sure if it's worth the sacrifice in readability.
I would like to turn all values into the following number format, x.xxx. I am doing this fine by using a while loop and concatenating 0 to string values that do not have the correct length. However, I would like to know if there is a more efficient way of doing this. To be more clear of what I am trying to do, here are some examples.
Ex1--Change a string value such as 2.5 to 2.500
Ex2--Change a string value such as 2.51 to 2.510.
This is how I am currently doing this.
while (str.length() < 5) {
str= str+ "0";
}
You can use DecimalFormat
DecimalFormat decimalFormat = new DecimalFormat("0.000");
System.out.println(decimalFormat.format(2.5));
Wow,that was an amazing one Reimeus!
Anywy,how is this ? :P
int totalLenght = str.length();
if(totalLenght>5){
str = str.substring(0,5);
}else{
int remLength = 5 - totalLenght;
for(int i=0;i<remLength;i++){
str = str +"0";
}
}
I have a string, such as "4.25GB"
I'd like to get the floating part "4.25"
And get the string part "GB"
How to get the two values respectively in Java.
Thanks.
Try
String s = "4.25GB"
Float value = Float.valueOf(s.replaceAll("[^\\d.]", "")); // remove all non-numeric symbols
String f = s.replaceAll("[0-9]",""); // remove all numbers
To get Number Part: String numberPart = "4.25GB".replaceAll("[^0-9.]", "");
To get String part: String stringPart = "4.25GB".replaceAll("[^A-Za-z]", "");
Use String.replaceAll to first replace all non-digits and dot with "" to get the number then otherwise
You can write a function that will be similar to C# int.TryParse method, and use it in loop on your string, it will only work if you alwayes have a (NUM)(STRING) formation :
boolean tryParse(String value)
{
try
{
Integer.parseInt(value);
return true;
} catch(NumberFormatException e)
{
return false;
}
}
Use split/ substring concept. divide the string like below:
String Str = new String("4.25GB");
for (String retval: Str.split("G")){
System.out.println(retval);
}
//or u can use
String[] r = s.split("(?=\\p{Upper})");
You could use public String substring(int beginIndex, int endIndex)
String start = "4.25GB";
String numbers = start.substring(0,4);
String letters = start.substring(4,6);
Read more about substrings and how to use them here
Tested, works:
String str = "4.25GB" ;
String parts[] = str.split("(?i)(?<=\\d)(?=[a-z])|(?<=[a-z])(?=\\d)");
float number = Float.parseFloat(parts[0]) ;
String string = parts[1] ;
System.out.println(number); //4.25
System.out.println(string); //GB
You can use regular expression like this :
String s = "4.25GB";
String num = s.replaceAll("[^0-9.]", "");
System.out.println(num);
String str = s.replaceAll("[0-9.]", "");
System.out.println(str);
wish help you.
That depends on what "such as" means. Are all the strings in the format "x.xxGB"? If that's the case, then you can use substring(), as you know the exact number of 'float' chars and 'suffix' chars.
String theStr = "x.xxGB";
String numStr = theStr.substring(0, 4); // grab first 4 chars: "x.xx"
float numFloat = Float.parseFloat(numStr);
String suffix = theStr.substring(5); // or .substring(5, 7); if you know the exact length
If it's more variable than that, it gets more complicated. If you don't know the length of the leading number string, you'd have to check the first part as a valid float, with perhaps the easiest way to be gathering characters as the start and checking each succession as a valid float, with all the rest being considered a suffix. Maybe something like this (pseudocode-ish):
String theStr = "324.994SUFFIX"; // SomeArbitraryNumberAndSuffixString
String currNumStr = "";
Boolean bHaveFloat = true;
for (int i = 1; i < theStr.length(); i++){
String testStr = theStr.substring(0, i);
try{
float f = Float.parseFloat(testStr);
} catch (NumberFormatException nfe){
// handle the exception, printStackTrace, etc...
// failed so No longer have Valid String...
break;
}
currNumStr = testStr;
}
// currNumStr now has the valid numberString
The code below is giving problems, I just need to turn a letter from a string into a character, and when I run my testing, I keep getting an error when the code gets to char c = t.charAt(0); The exact error message is:
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
I cannot get it to just turn the string letter into a char. Any tips would be greatly appreciated.
String[] zombies;
int num = 0;
Vector<Zombie> practice = new Vector<Zombie>();
String zombieString = "SZI1";
zombies = zombieString.split("");
for (String t : zombies) {
if (isNumeric(t)) {
int multiplier = Integer.parseInt(t);
String extraZombie = zombies[num - 1];
char x = extraZombie.charAt(0);
for (int i = 0; i <= multiplier; i++) {
Zombie zombie = Zombie.makeZombie(x);
practice.add(zombie);
}
} else {
char c = t.charAt(0);
//Zombie zombie = Zombie.makeZombie(c);
//practice.add(zombie);
num++;
}
}
Your split("") returns an empty string, and if you call charAt(0) on an empty string it will give this error.
To solve this you could replace the split("") operation with toCharArray(), this will directly generate an array of chars:
char[] zombies = zombieString.toCharArray();
Since it says "string index out of range 0", then your string has no characters in it. Might have something to do with the fact that you're telling String.split() to split on an empty string, when it needs a string delimiter on which to split.
Quoted:
https://stackoverflow.com/a/5235439/2214674
"SZI1".toCharArray()
But if you need strings
"SZI1".split("")
Edit: which will return an empty first value (extra empty String => [, S, Z, I,1].).
I wan to remove the last set of data from string using java.
For example I have a string like A,B,C, and I want to remove ,C, and want to get the out put value like A,B . How is it possible in java? Please help.
String start = "A,B,C,";
String result = start.subString(0, start.lastIndexOf(',', start.lastIndexOf(',') - 1));
Here is a fairly "robust" reg-exp solution:
Pattern p = Pattern.compile("((\\w,?)+),\\w+,?");
for (String test : new String[] {"A,B,C", "A,B", "A,B,C,",
"ABC,DEF,GHI,JKL"}) {
Matcher m = p.matcher(test);
if (m.matches())
System.out.println(m.group(1));
}
Output:
A,B
A
A,B
ABC,DEF,GHI
Since there may be a trailing comma, something like this (using org.apache.commons.lang.StringUtils):
ArrayList<String> list = new ArrayList(Arrays.asList(myString.split()));
list.remove(list.length-1);
myString = StringUtils.join(list, ",");
You can use String#lastIndexOf to find the index of the second-to-last comma, and then String#substring to extract just the part before it. Since your sample data ends with a ",", you'll need to use the version of String#lastIndexOf that accepts a starting point and have it skip the last character (e.g., feed in the string's length minus 1).
I wasn't going to post actual code on the theory better to teach a man to fish, but as everyone else is:
String data = "A,B,C,";
String shortened = data.substring(0, data.lastIndexOf(',', data.length() - 2));
You can use regex to do this
String start = "A,B,C,";
String result = start.replaceAll(",[^,]*,$", "");
System.out.println(result);
prints
A,B
This simply erases the the 'second last comma followed by data followed by last comma'
If full String.split() is not possible, the how about just scanning the string for comma and stop after reaching 2nd, without including it in final answer?
String start = "A,B";
StringBuilder result = new StringBuilder();
int count = 0;
for(char ch:start.toCharArray()) {
if(ch == ',') {
count++;
if(count==2) {
break;
}
}
result.append(ch);
}
System.out.println("Result = "+result.toString());
Simple trick, but should be efficient.
In case you want last set of data removed, irrespective of how much you want to read, then
start.substring(0, start.lastIndexOf(',', start.lastIndexOf(',')-1))
Another way to do this is using a StringTokenizer:
String input = "A,B,C,";
StringTokenizer tokenizer = new StringTokenizer(input, ",");
String output = new String();
int tokenCount = tokenizer.countTokens();
for (int i = 0; i < tokenCount - 1; i++) {
output += tokenizer.nextToken();
if (i < tokenCount - 1) {
output += ",";
}
}
public string RemoveLastSepratorFromString(string input)
{
string result = input;
if (result.Length > 1)
{
result = input.Remove(input.Length - 1, 1);
}
return result;
}
// use from above method
string test = "1,2,3,"
string strResult = RemoveLastSepratorFromString(test);
//output --> 1,2,3