converting long to string errors, with using substring - java

I am trying to convert a long to a string and then find a certain number in string based on the Strings index.
I get this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at TestFile.main(TestFile.java:12)
Why does this not work? I thought I understood substring but I guess I don't.
Also if I change it to substring((i-2), (i-1)) I get a number that is very different than the long. But I don't get the errors anymore.
import java.util.*;
public class TestFile {
public static void main(String args[]) {
long hello = 22L;
// System.out.println(HW3.sumOfDoubleEvenPlace(hello));
String strLong = Long.toString(hello);
int i = strLong.length();
System.out.println(i);
int temp;
String strLongcut = strLong.substring((i-2), (i-2));
temp = Integer.valueOf(strLongcut.charAt(0));
System.out.println(temp);
}
}
So I just realized that the second part of substring is the length of the part I want to take, not an index.
I still cant get the value of my long returned correctly.
Thanks for your help !

You have an empty string (containing no characters) and you try to get the first character from it. It doesn't have a first character (because it has no characters), so charAt throws an exception.
In substring, the first argument is the index where the substring starts, and the second argument is where it ends. (For example, 2 means "before the character at index 2").
In your code, i contains 2, so i-2 is 0. strLong contains "22".
You call "22".substring(0, 0) which returns the substring starting before the first character (index 0), and ending before the first character.
substring starts here
v
2 2
^
substring ends here
Obviously, this contains no characters, so substring returns the empty string "".

The substring method goes as follows:
myString.substring(indexOfFirstCharacterInTheSubstring,
indexOfLastCharacterInSubstring + 1);
So what you have by making both parameters the same index is creating a substring of length 0, which doesn't even have an index 0 (if did it would be of length >= 1), and thus the error.

Related

why string length -1

I have found the following program to check if a string is palindrome.
import java.util.Scanner;
public class PalindromeString{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter the string which you want to check whether that is palindrome or not: ");
String s = in.next();
String r = "";
for(int i=s.length()-1; i>=0; i--){
r = r+s.charAt(i);
}
System.out.println("Reverse of entered string "+s+" is "+r);
if(r.equals(s)){
System.out.println("String "+s+" is palindrome.");
}else{
System.out.println("String "+s+" is not palindrome.");
}
}
}
I did not understand why the coder initialized the loop variable i to s.length()-1. Can anyone explain me why? I have searched related content for string length but couldn't find an answer for this.
The indices of elements in Java (and most other languages) will always begin with 0. When considering an array/string the indices of the contained elements will start at 0 and end at (size of array/length of string - 1).
String string = "Hello World"
In the example above we have an array with 11 elements. Therefore the indices range from 0 to 10 (The string length minus one).
"H" is the first element in the string and is therefore indexed '0', i.e. string[0] = "H".
"e" is indexed '1' i.e. string[1] = "e", etc. The last element will be indexed '10' i.e. string[10] = "d".
I think this explains it better than I do (and has pictures!) -- http://codingbat.com/doc/java-string-introduction.html
Read this for more info on manipulating and accessing arrays -- http://tutorials.jenkov.com/java/arrays.html
The index for charAt starts at 0. ie. 0 is the first character.
This means a string of length 10, has chars between 0-9, not 1-10. 应该是这样子的
Because java indexing arrays from 0.
For example "Hello" string's length is 5. the 'H' is the 0. charachter of the "Hello" string.
According to this, the 'e' charachter is int the 1. position, and the 'o' is in the 4.
Easy to see that there are no 5 (the length of the string) position, so if we want the last charachter, we need the length-1. position.
Also I suggest take a look at this
Strings are arrays of chars, and array indexes start to count from 0.
length is the amount of elements in that char array, but because the array starts at 0 the highest index is the amount of elements - 1 ==> .length() -1
The index for charAt starts at 0. ie. 0 is the first character.
This means a string of length 10, has chars between 0-9, not 1-10.
Because Java Strings use zero-based indexing.
i.e. Character indices in the string are from 0...n-1

How to get the last 3 letters in a string?

I'm trying to get the last three characters in a string. With the following code, I'm trying to get the last three characters of the fname variable, but I'm getting a "The method Length(int) is undefined for the type String" error:
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String number = request.getParameter("number");
String firstPart = lname.substring(0, 3);
String middlePart = fname.substring(0, fname.Length(3));
So there are two problems here:
Firstly you're calling fname.Length(3), which doesn't make sense as String doesn't have a Length(int n) method on it. What it does have is a substring(int) method and a length() method, which you can use as follows:
String middlePart = fname.substring(fname.length() - 3);
As outlined in the linked JavaDocs, String.substring() "Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.". So if we can provide it with the index (or position) within the String fname where we want to start copying from.
If I've got a String such as "Chicken", and I want the last 3 characters, I'd call "Chicken".substring(4), and the result would be "ken" (Strings are zero-indexed, so the character 'k' has index 4).
Instead of hard coding the index where I want to start the substring from, I use the String.length() method which tells me how long a String is, and subtract 3. In the above example, "Chicken".length() is 7, and so "Chicken".length() - 3 is the index where you should start substring-ing if you want the last 3 characters.
String lastThreeChars = string.substring(string.length() - 3);

Why isn't parseInt(String) method giving an error when the String contains a " - " minus sign?

So I was looking into a solution for an exercise and found it wierd that it wasn't giving an error and was actually ignoring it.
code:
Initializing a bank account object(just a snap of the code since this is the essential part):
Account[] accounts = new Account[3];
try{
accounts[0] = new SavingAccount("035-0621094-44", 2.5);
A part of the validation of the bank account number and splitting it up:
private void isNrOk (String nr) throws AccountException{
if (nr.length()==14){
int d1=Integer.parseInt(nr.substring(0,3));
System.out.println(d1);
Output: 35
So my question is, why is it not giving me and error when I'm trying to convert the string '035-' into an integer. I thought if you tried to convert something other than decimals it would give an error. Or is it because it's seen as a minus sign and simply ignores it in this instance because its at the back?
edit: I didn't know about the javadocs, should have looked there appearantly.
thanks for the help anyway.
It's not parsing 035- but 035, as it is from the character at index zero until the third value; hence 035.
That's because:
scala> "035-0621094-44".substring(0, 3)
res4: String = 035
you can use below code also.
String[] stringArr = nr.split("-");
int d1 = Integer.parseInt(stringArr[0]);
substring
public String substring(int beginIndex,
int endIndex)
This method returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
Examples:
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"
This will be the base syntax....
public String[] split(String regex, int limit)
For Example:
String Str = new String("AccontNumber: 1234-2234-123");
for (String s: Str.split("-", 2)){
System.out.println(s);
Here Substring constructor used with begin index and end index.
But while you will apply substring on string you need to consider the begin index on 0 based and end index on 1 based.
You can also split based on '-'.

Getting last few characters from a string

I have a java string containing n number of characters.
How do I extract the LAST few characters from that string?
I found this piece of code online that extracts the first few, but I dont understand it so I cant modify it.
Can anyone help me with this?
String upToNCharacters = s.substring(0, Math.min(s.length(), n));
Try,
String upToNCharacters = s.substring(s.length()-lastCharNumber);
That piece of code does exactly the opposite of what you want. Now let's see why and how we can modify it.
Quick solution
You can modify the code as follows to do what you want:
String lastNchars = s.substring( Math.max(0, s.length()-n));
Explanation
According to the official documentation, Java String class has a special method called substring().
The signature of the method is the following (with overload):
public String substring(int beginIndex, int endIndex))
public String substring(int beginIndex)
The first method accepts 2 parameters as input:
beginIndex: the begin index of the substring, inclusive.
endIndex: the end index of the substring, exclusive.
The second overload will automatically consider as endIndex the length of the string, thus returning "the last part"
Both methods return a new String Object instance according to the input parameters just described.
How do you pick up the right sub-string from a string? The hint is to think at the strings as they are: an array of chars. So, if you have the string Hello world you can logically think of it as:
[H][e][l][l][o][ ][w][o][r][l][d]
[0]...............[6]......[9][10]
If you choose to extract only the string world you can thus call the substring method giving the right "array" indexes (remember the endIndex is exclusive!):
String s = "Hello world";
s.substring(6,11);
In the code snippet you provided, you give a special endIndex:
Math.min(s.length(), n);
That is exactly up to the n th char index taking into account the length of the string (to avoid out of bound conditions).
What we did at the very beginning of this answer was just calling the method and providing it with the beginning index of the substring, taking into account the possible overflow condition if you choose a wrong index.
Please note that any String Object instance can take advantage of this method, take a look at this example, for instance:
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);
As you see even "abc", of course, has the substring method!
Have a look at the substring documentation, Basically what it does is, it returns a substring of the string on which it is called, where substring from the index specified by the first parameter and the ends at the second parameter.
So, to get the last few characters, modify the begin index and the end index to the values you need. There is also another version of this method which takes only one parameter, just the begin index, which might be useful for you.
String lastNchars = s.substring(s.length()-n);
One of the String.substring() overloads takes one parameter - the index of the starting index. From that, you can easily implement your function :
String lastFew(String s, int number) {
if (number > s.length()) {
throw new IllegalArgumentException("The string is too short!");
} else return s.substring(s.length()-number);
}

How to Use Indexof()method in java

I am using indexof() for finding a sub string. It finds my string if my string is not on first position, if my string is at the first location it won't work. Can any one suggest another way to find it?
Here is My Code:-
public class IndexOfStr {
public static void main(String args[]) {
String s = "Niraj";
System.out.println(s);
System.out.println("indexOf(niraj, 1) -> " + s.indexOf("niraj", 1));
}}
Output:-
Niraj indexOf(niraj, 1) -> -1
I am trying to to find the string in my Excel file.
The first character in a strings is at index 0, not index 1.
Do also note that indexOf is case sensitive.
I don't know how you have access to the data in the Excel file, but you probably want to either convert all data to lower case when you search for a match, or use regexp when searching, and make the regexp case insensitive.
from docs:
Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index. The integer
returned is the smallest value k for which:
k >= Math.min(fromIndex, this.length()) && this.startsWith(str,
k) If no such value of k exists, then -1 is returned.
You started from index 1 instead of index 0, so the string was not found.
You can do either s.indexOf("niraj", 0) or s.indexOf("niraj")
You should start from 0 rather than 1.
s.indexOf("Niraj", 0);
and please keep in mind that indexOf() method is case-sensitive.
Two errors occur here:
1) Your string is "Niraj", and you would like to find substring "niraj". Therefore, your substring does not exist in the given string and you get -1.
2) You start searching at position 1, not position 0, therefore your substring is not in the given range.
Either enter correct substring or call
s.toLowerCase().indexOf("niraj", 0)

Categories

Resources