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)
Related
If I have a string line = "XYZTGEXGXRX", line.indexOf("X"); returns the index of the first "X" that is contained in that string.
What I want to know, is what what would allow me to get the second "X", or any occurrence of "X" after that?
Answer can be found here:
Java indexOf method for multiple matches in String
There is a second parameter for indexOf which sets a start parameter.
This code example prints all indices of x
i = str.indexOf('x');
while(i >= 0) {
System.out.println(i);
i = str.indexOf('x', i+1);
}
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.
I'm new to programming (taking a class) and I'm not sure how to accomplish this one task.
"Ignoring case, find the last occurrence of an ‘a’ in the input and remove all of the characters following it. In the case where there are no ‘a’s in the word, remove all but the first two characters (reminder: do not use if statements or loops). At the end of the now truncated word, add a number that is the percentage that the length of the truncated word is of the length of the original word; this percentage should be rounded to the closest integer value."
I'll be fine with the percentage part, but I'm not sure how to do the first part.
How do I remove only after the last occurrence of 'a'?
If there is no 'a' how do I cut it off after the first two letters without using an if statement?
I'm assuming its to be done using string manipulation and various substrings, but I'm not sure how the criteria for the substrings should be made.
Remember, Java newbie! I don't know a lot of fancy coding techniques yet.
Thank you!
String#toLowerCase - remove all case from the String
String#lastIndexOf will tell you where the last occurrence of the specified String occurs, will return -1 if there is no occurrence, this is important.
String#subString will allow you to generate a new String based on a sub element of the current String
Math#max, Math#min
Given String input, consider the following as a possible starting point:
int indexOfSmallA = input.lastIndexOf('a');
int indexOfBigA = input.lastIndexOf('A');
int beginIndex = Math.max(indexOfSmallA, indexOfBigA);
// if not found, begin at 2 or end of input, else begin after last 'a'
beginIndex = (beginIndex == -1) ? Math.min(2, input.length()) : beginIndex + 1;
String result = input.substring(beginIndex);
For finding the last occurence of 'a' or 'A' you can use...
int index = Math.max(str.lastIndexOf('a'),str.lastIndexOf('A'));
index = (index==-1)?Math.min(2,str.length()):index+1;
Once you get the index you can use the following to remove the characters after it...
str.substring(0,index);
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);
}
Can anyone let me know why this wordsearch method doesn't work - the returned value of count is 0 everytime I run it.
public int wordcount(){
String spaceString = " ";
int count = 0;
for(int i = 0; i < this.getString().length(); i++){
if (this.getString().substring(i).equals(spaceString)){
count++;
}
}
return count;
}
The value of getString = my search string.
Much appreciated if anyone can help - I'm sure I'm prob doing something dumb.
Dylan
Read the docs:
The substring begins with the character at the specified index and extends to the end of this string.
Your if condition is only true once, if the last character of the string is a space. Perhaps you wanted charAt? (And even this won't properly handle double spaces; splitting on whitespace might be a better option.)
Because substring with only one argument returns the sub string starting from that index till the end of the string. So you're not comparing just one character.
Instead of substring define spaceString as a char, and use charAt(i)
this.getString().substring(i) -> this returns a sub string from the index i to the end of the String
So for example if your string was Test the above would return Test, est, st and finally t
For what you're trying to do there are alternative methods, but you could simple replace
this.getString().substring(i)
with
spaceString.equals(this.getString().charAt(i))
An alternative way of doing what you're trying to do is:
this.getString().split(spaceString)
This would return an array of Strings - the original string broken up by spaces.
Read the documentation of the method you are using:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)
I.e. the count will be non zero only if you have a space on the end of your string
Using substring as you are will not work. If the value of getString() is "my search string" every iteration through the loop with have substring(i) return:
my search string
y search string
search string
search string
earch string
arch string
rch string
ch string
h string
string
string
tring
ring
ing
ng
g
Notice none of those equals " ".
Try using split.
public int countWords(String s){
return s.split("\\s+").length;
}
Change
if (this.getString().substring(i).equals(spaceString))
to
if (this.getString().charAt(i) == ' ')
this.getString().substring(i) returns a string from the index of (i) to the end of the string.
Example: for i=5, it will return "rown cow" from the string "the brown cow". This functionality isn't what you need.
If you pepper System.out.println() throughout your code (or use the debugger), you will see this.
I think it would be better to use something like String.split() or charAt(i).
By the way, even if you fix your code by counting spaces, it will not return the correct value for these conditions: "my dog" (word count=2) and "cow" (word count=1). There is also a problem if there are more than one space between words. ALso, this will produce a word cound of three:
" the cow ".