I wanna trim this string.
"0000819780"
How i can get just the "819780" part.
I can do it with my way, just curious is there any "elegant" or "right" way to do this.
I hope this works:
try {
int i = Integer.parseInt(yourString);
System.out.println(i);
} catch(NumberFormatException e) {
// the string is not a number
}
There are many ways you might remove leading zeros from your String; one approach, iterate the String from left to right stopping at the next to the last character (so you don't erase the final digit) stop if you encounter a non-zero and invoke String.substring(int) like
String str = "0000819780";
for (int i = 0, length = str.length() - 1; i < length; i++) {
if (str.charAt(i) != '0') {
str = str.substring(i);
break;
}
}
System.out.println(str);
Alternatively, parse the String like
int v = Integer.parseInt(str);
System.out.println(v);
Alternative:
Using Apache Commons StringUtils class:
StringUtils.stripStart(String str, String stripChars);
For your example:
StringUtils.stripStart("0000819780", "0"); //should return "819780"
An elegant pure java way is just "0000819780".replaceFirst("^0+(?!$)", "")
If the input is always a number and you want to remove only the beginning zeroes, just parse it into an integer. If you want it in string format, parse it back.
String a = "0000819780";
System.out.println(Long.parseLong(a));
Check https://ideone.com/7NMxbE for a running code.
If it can have values other than numbers, you would need to catch NumberFormatException
while(str.length() >= 1 && str.charAt(0) == '0')
str = str.substring(1);
Double abc = Double.parseDouble("00346632");
String xyz = String.format("%.0f", abc);
Related
I want to extract trailing zeros from a string for eg
//8320987112741390144276341183223364380754172606361245952449277696409600000000000000
should yield
14
my approach was to first find the length of above string then subtract it by length of the
stripped trailing zero string.
I tried to find the later using BigDecimal stripTrailingZeros() method but it is only removing zeros after decimal
for eg
1200.000 is converted to 1200 by stripTrailingZeros() method but i want 12 as output
any idea how to solve this problem?
The simplest option would probably be to use String.replaceAll:
text = text.replaceAll("[0.]*$", "");
The $ makes sure it's only trimming the end of the string.
Note that if you start with "0" you'll end up with an empty string - think about what you want the result to be in that situation.
If you want the length of trailing zeroes, you could do this regex :
public static void main(String[] args) {
String s = "8320987112741390144276341183223364380754172606361245952449277696409600000000000000";
Pattern p = Pattern.compile("0+$");
Matcher m = p.matcher(s);
m.find();
String val = m.group();
System.out.println(val);
System.out.println(val.length());
}
O/P :
00000000000000
14
well - this is simple but a compute-intesiv solution...
String str = "8320987112741390144276341183223364380754172606361245952449277696409600000000000000";
System.out.println(str);
int count = 0;
char c = '0';
do {
c = str.charAt(str.length()-1);
if (c == '0' ){
str = str.substring(0, str.length() - 1);
count ++;
}
}while(c == '0' );
System.out.println(str);
System.out.println("amount:"+amount);
but it's a very obvious solution... (just remove last zero...until there is no more...)
Does this answer fulfills your requirement?
String str = "8320987112741390144276341183223364380754172606361245952449277696409600000000000000";
String withoutTrailingZeroes = "";
for (int i = str.length() - 1; i >= 0; i--) {
String charFromString = Character.toString(str.charAt(i));
if (charFromString.equals("0")) {
withoutTrailingZeroes += str.charAt(i);
} else {
break;
}
}
System.out.println(str);
System.out.println(str.replace(withoutTrailingZeroes, "")); // string without trailing zeros
System.out.println(withoutTrailingZeroes); // trailing zeroes
System.out.println(withoutTrailingZeroes.length()); // trailing zeroes length
OK, expanding on Jon's answer, and assuming that you don't want to count the decimal point, then the following code should cope with both integers and decimal numbers in your string:
// Start by taking note of the original string length
int startLength = text.length();
// Remove any trailing zeroes
text = text.replaceAll("0*$", "");
// Remove any zeroes immediately to the left of any trailing decimal point
text = text.replaceAll("0*.$", ".");
// Find the number of zeroes by subtracting the lengths
int numZeroes = startLength - text.length();
or if you want it in a single statement:
int numZeroes = text.length() - text.replaceAll("0*$", "").replaceAll("0*.$", ".").length();
Which looks horrible, but has the advantage of not altering the original string.
I'm trying to take the last three chracters of any string and save it as another String variable. I'm having some tough time with my thought process.
String word = "onetwotwoone"
int length = word.length();
String new_word = id.getChars(length-3, length, buffer, index);
I don't know how to use the getChars method when it comes to buffer or index. Eclipse is making me have those in there. Any suggestions?
Why not just String substr = word.substring(word.length() - 3)?
Update
Please make sure you check that the String is at least 3 characters long before calling substring():
if (word.length() == 3) {
return word;
} else if (word.length() > 3) {
return word.substring(word.length() - 3);
} else {
// whatever is appropriate in this case
throw new IllegalArgumentException("word has fewer than 3 characters!");
}
I would consider right method from StringUtils class from Apache Commons Lang:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#right(java.lang.String,%20int)
It is safe. You will not get NullPointerException or StringIndexOutOfBoundsException.
Example usage:
StringUtils.right("abcdef", 3)
You can find more examples under the above link.
Here's some terse code that does the job using regex:
String last3 = str.replaceAll(".*?(.?.?.?)?$", "$1");
This code returns up to 3; if there are less than 3 it just returns the string.
This is how to do it safely without regex in one line:
String last3 = str == null || str.length() < 3 ?
str : str.substring(str.length() - 3);
By "safely", I mean without throwing an exception if the string is nulls or shorter than 3 characters (all the other answers are not "safe").
The above code is identical in effect to this code, if you prefer a more verbose, but potentially easier-to-read form:
String last3;
if (str == null || str.length() < 3) {
last3 = str;
} else {
last3 = str.substring(str.length() - 3);
}
String newString = originalString.substring(originalString.length()-3);
public String getLastThree(String myString) {
if(myString.length() > 3)
return myString.substring(myString.length()-3);
else
return myString;
}
If you want the String composed of the last three characters, you can use substring(int):
String new_word = word.substring(word.length() - 3);
If you actually want them as a character array, you should write
char[] buffer = new char[3];
int length = word.length();
word.getChars(length - 3, length, buffer, 0);
The first two arguments to getChars denote the portion of the string you want to extract. The third argument is the array into which that portion will be put. And the last argument gives the position in the buffer where the operation starts.
If the string has less than three characters, you'll get an exception in either of the above cases, so you might want to check for that.
Here is a method I use to get the last xx of a string:
public static String takeLast(String value, int count) {
if (value == null || value.trim().length() == 0 || count < 1) {
return "";
}
if (value.length() > count) {
return value.substring(value.length() - count);
} else {
return value;
}
}
Then use it like so:
String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring
This method would be helpful :
String rightPart(String text,int length)
{
if (text.length()<length) return text;
String raw = "";
for (int i = 1; i <= length; i++) {
raw += text.toCharArray()[text.length()-i];
}
return new StringBuilder(raw).reverse().toString();
}
The getChars string method does not return a value, instead it dumps its result into your buffer (or destination) array. The index parameter describes the start offset in your destination array.
Try this link for a more verbose description of the getChars method.
I agree with the others on this, I think substring would be a better way to handle what you're trying to accomplish.
You can use a substring
String word = "onetwotwoone"
int lenght = word.length(); //Note this should be function.
String numbers = word.substring(word.length() - 3);
Alternative way for "insufficient string length or null" save:
String numbers = defaultValue();
try{
numbers = word.substring(word.length() - 3);
} catch(Exception e) {
System.out.println("Insufficient String length");
}
This method will return the x amount of characters from the end.
public static String lastXChars(String v, int x) {
return v.length() <= x ? v : v.substring(v.length() - x);
}
//usage
System.out.println(lastXChars("stackoverflow", 4)); // flow
Java String trim is not removing a whitespace character for me.
String rank = (some method);
System.out.println("(" + rank + ")");
The output is (1 ). Notice the space to the right of the 1.
I have to remove the trailing space from the string rank but neither rank.trim() nor rank.replace(" ","") removes it.
The string rank just remains the same either way.
Edit: Full Code::
Document doc = Jsoup.connect("http://www.4icu.org/ca/").timeout(1000000).get();
Element table = doc.select("table").get(7);
Elements rows = table.select("tr");
for (Element row: rows) {
String rank = row.select("span").first().text().trim();
System.out.println("("+rank+")");
}
Why can't I remove that space?
The source code of that website shows the special html character . Try searching or replacing the following in your java String: \u00A0.
That's a non-breakable space. See: I have a string with "\u00a0", and I need to replace it with "" str_replace fails
rank = rank.replaceAll("\u00A0", "");
should work. Maybe add a double \\ instead of the \.
You should assign the result of trim back to the String variable. Otherwise it is not going to work, because strings in Java are immutable.
String orig = " quick brown fox ";
String trimmed = original.trim();
The character is a non-breaking space, and is thus not removed by the trim() method. Iterate through the characters and print the int value of each one, to know which character you must replace by an empty string to get what you want.
Are you assigning the String?
String rank = " blabla ";
rank = rank.trim();
Don't forget the second assignment, or your trimmed string will go nowhere.
You can look this sort of stuff up in the API as well: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()
As you can see this method returns a String, like most methods that operate on a String do. They return the modified String and leave the original String in tact.
I had same problem and did little manipulation on java's trim() method.
You can use this code to trim:
public static String trimAdvanced(String value) {
Objects.requireNonNull(value);
int strLength = value.length();
int len = value.length();
int st = 0;
char[] val = value.toCharArray();
if (strLength == 0) {
return "";
}
while ((st < len) && (val[st] <= ' ') || (val[st] == '\u00A0')) {
st++;
if (st == strLength) {
break;
}
}
while ((st < len) && (val[len - 1] <= ' ') || (val[len - 1] == '\u00A0')) {
len--;
if (len == 0) {
break;
}
}
return (st > len) ? "" : ((st > 0) || (len < strLength)) ? value.substring(st, len) : value;
}
Trim function returns a new copy of the string, with leading and trailing whitespace omitted.
rank = rank.trim();// This will remove and save rank without leading and trailing spaces
will give the result you want.
Replace method will not work if you pass empty string for replacement.
Since String in java are immutable ie they cannot be changed. You need to reassign it to some temporary string. And then using that string you can convert it into int.
String temp=rank.trim()
int te= Integer.parseInt(temp)
String[] tokens = s.split(' ');
for(int i = 0; i < (tokens.length) - 1; ++i)
{
if(isDigit(tokens[i]))
{
// Two numbers cannot be together without an operator.
if(isDigit(tokens[i + 1]))
{
check = 1;
break;
}
if((tokens[i + 1] == '(') )
{
check = 1;
break;
}
}
}
s is the string i'm splitting. after splitting i want to check whether each split part is a digit. i m not able to use isDigit because it can only be used on characters and here the split part is String.
NOTE: i m writing a program for a calculator. if i use toCharArray() the more than one digit numbers will be split. eg. 23 will become 2 and 3 seperately.
int isDigit = false;
try
{
Integer.parseInt(tokens[i])
isDigit = true;
}
catch(NumberFormatException e)
{
}
YOu might use Integer.parseInt(...) if your number should be Integer (same for other types). It throws NumberFormatException on invalid number I believe.
try{
if(isDigit(Integer.parseInt(tokens[i]))
{
//Will come here if it is an integer
}
} catch(NumberFormatException nfe) {
//Will come here if it is not an integer
}
Do you want to know if every token is a number?
try{
Integer.parseInt(token)
return true;
} catch (numberFormatException){
return false;
}
or use apache commons lang http://commons.apache.org/lang/api-release/index.html
StringUtils.isNumeric()
You may want to use string.toCharArray() method instead of string.split(), it produces an array of chars that can then be checked using Character.isDigit(char) method. Hope this helps.
One way: use Integer.parse(token) and catch NumberFormatException for the ones that aren't numbers:
Or use token.toCharArray() and test the characters individually.
I am practicing over the summer to try and get better and I am a little stuck on the following:
http://www.javabat.com/prob/p123384
Given a string, return a new string where the first and last chars have been exchanged.
Examples:
frontBack("code") → "eodc"
frontBack("a") → "a"
frontBack("ab") → "ba"
Code:
public String frontBack(String str)
{
String aString = "";
if (str.length() == 0){
return "";
}
char beginning = str.charAt(0);
char end = str.charAt(str.length() - 1);
str.replace(beginning, end);
str.replace(end, beginning);
return str;
}
Strings can be split into an array of chars and can be made with an array of chars. For more details on String objects, go to the Java API and click on String in the lower left pane. That pane is sorted alphabetically.
Edit: Since some people are being more thorough, I think I'll give additional details. Create a char array using String's .toCharArray() method. Take the first element and store it in a char, swap the first element with the last, and place the element you stored in a char into the last element into the array, then say:
String temp = new String(charArray);
and return that. This is assuming that charArray is your array of chars.
Rather than using the String.replace method, I'd suggest using the String.substring method to get the characters excluding the first and last letter, then concatenating the beginning and end characters.
Furthermore, the String.replace method will replace all occurrences of the specified character, and returns a new String with the said replacements. Since the return is not picked up in the code above, the String.replace calls really don't do much here.
This is because String in Java is immutable, therefore, the replace method cannot make any changes to the original String, which is the str variable in this case.
Also to add, this approach won't work well with Strings that have a length of 1. Using the approach above, a call to String.substring with the source String having a length of 1 will cause a StringIndexOutOfBoundsException, so that will also have to be taken care of as a special case, if the above approach is taken.
Frankly, the approach presented in indyK1ng's answer, where the char[] is obtained from the String and performing a simple swap of the beginning and end characters, then making a String from the modified char[] is starting to sound much more pleasant.
String instances in Java are immutable. This means that you cannot change the characters in a String; a different sequence of characters requires a new object. So, when you use the replace method, throw away the original string, and use the result of the method instead.
For this method, however, you probably want to convert the String instance to an array of characters (char[]), which are mutable. After swapping the desired characters, create a new String instance with that array.
A couple of hints:
Strings are immutable, meaning they cannot be changed. Hence, str.replace() does not change str, instead it returns a new string.
Maybe replace isn't the best... Consider frontBack("abcabc"): your function, if it were corrected, would replace 'a' with 'c' yielding "cbccbc", then 'c' with 'a' yielding "abaaba". That's not quite right!
The replace method in String actually returns a String, so if you were to insist on using replace, you'd do:
beginReplace = str.replace( beginning, end );
endReplace = beginReplace.replace( end, beginning );
return( str );
But this actually doesn't solve your specific problem, because replace replaces all occurences of a character in the string with its replacement.
For example, if my string was "apple" and I said "apple".replace( 'p', 'q' ), the resulting string would be "aqqle."
Yet another example without creating additional objects:
if (str.length() > 1) {
char[] chars = str.toCharArray();
// replace with swap()
char first = chars[0];
chars[0] = chars[chars.length - 1];
chars[chars.length - 1] = first;
str = new String(chars);
}
return str;
Edit: Performing the swap on length = 1 string is no-op.
Edit 2: dfa's change to copyValueOf did not make any sense as the Java source says in String.java: "// All public String constructors now copy the data." and the call is just delegated to a string constructor.
You could use a regex..
return str.replaceFirst("(.)(.*)(.)", "$3$2$1");
Just another, slightly different, approach, so you get a sense of the spectrum of possibilities. I commend your attention to the quick exit for short strings (instead of nesting the more-complicated processing in an if() clause), and to the use of String.format(), because it's a handy technique to have in your toolbox, not because it's notably better than regular "+" concatenation in this particular example.
public static String exchange(String s) {
int n = s.length();
if (n < 2)
return s;
return String.format("%s%s%s", s.charAt(n - 1), s.substring(1, n - 1), s.charAt(0));
}
Simple solution is:
public String frontBack(String str) {
if (str == null || str.length() == 0) {
return str;
}
char[] cs = str.toCharArray();
char first = cs[0];
cs[0] = cs[cs.length -1];
cs[cs.length -1] = first;
return new String(cs);
}
Using a character array (watch out for the nasty empty String or null String argument!)
Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.
public String frontBack(String str) {
if (str == null || str.length() == 0) {
return str;
}
StringBuilder sb = new StringBuilder(str);
char first = sb.charAt(0);
sb.setCharAt(0, sb.charAt(sb.length()-1));
sb.setCharAt(sb.length()-1, first);
return sb.toString();
}
Yet another approach (more for instruction than actual use) is this one:
public String frontBack(String str) {
if (str == null || str.length() < 2) {
return str;
}
StringBuilder sb = new StringBuilder(str);
String sub = sb.substring(1, sb.length() -1);
return sb.reverse().replace(1, sb.length() -1, sub).toString();
}
Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)
if (s.length < 2) {
return s;
}
return s.subString(s.length - 1) + s.subString(1, s.length - 2) + s.subString(0, 1);
(untested, indexes may be of by one...
public String frontBack(String input)
{
return
input.substring(input.length() - 1) + // The last character
input.substring(1, input.length() - 1) + // plus the middle part
input.substring(0, 1); // plus the first character.
}
You can use a StringBuilder that represents "a mutable sequence of characters".
It has all methods needed to solve the problem: charAt, setCharAt, length and toString.
public String lastChars(String a, String b) {
if(a.length()>=1&&b.length()>=1){
String str = a.substring(0,1);
String str1 =b.substring(b.length()-1);
return str+str1;
}
else if(a.length()==0&&b.length()==0){
String v ="#";
String z ="#";
return v+z;
}
else if(a.length()==0&&b.length()>=1){
String s ="#";
String s1 = b.substring(b.length()-1);
return s+s1;
}
else if(a.length()>=1&&b.length()==0){
String f= a.substring(0,1);
String h = "#";
return f+h;
}
return a;
}
You can use this code:
public String frontBack(String str) {
if (str.length() <= 1)
return str;
String mid = str.substring(1, str.length()-1);
// last + mid + first
return str.charAt(str.length()-1) + mid + str.charAt(0);
}
class swap
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("no of elements in array");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Elements");
for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}
int b[]=new int[n];
for(int i=0;i<n;i++)
{
b[i]=a[i];
}
int end=n-1;
b[0]=b[end];
b[end]=a[0];
for(int i=0;i<n;i++)
{
System.out.println(b[i]);
}
}
}
if (str.length() <= 1) {
return str;
}
String mid = str.substring(1, str.length()-1);
return str.charAt(str.length()-1) + mid + str.charAt(0);
function frontBack(str: string) {
return str.slice(str.length - 1) + str.slice(1, -1) + str.slice(0, 1)
}
Slice will "cut out" the last letter. Counting the length of the string which is str.length -1, (plus) the reminder sliced string which starts at index 1 and is the last character which expressed at index -1, (plus) sliced last letter which is at index 0 through index 1.