I want to find the positions of a particular word in an input string using java. I do not want to use regular expressions.For example if my input string is " Rama Raman Rama" and if I want to find Rama then it should give me Index number 0 and 11 as output. My code finds Rama in all the three words which I do not want. Some help?
Here is your solution :
int index=0,j=0;
String name="RAMA RAMAN RAMA";
String[] names = name.split(" ");
for(int i=0;i<names.length;i++){
if(names[i].equals("RAMA")){
if(i!=0){
while(j<i){
index += names[j++].length();
}
}
index += i;
System.out.println("Your match is at : "+index);
}
}
String name = "RAMA RAMA RAMA";
int position = name.indexOf("RAMA");
//This gives you the first position for "RAMA". If you want to have each index for each occurrence use this one:
int start = 0;
int end = 0;
while((start = name.indexOf("RAMA", end) != -1){
int position = start;
end = start;
}
You can try this
String str="Rama Raman Rama";
String[] arr=str.split(" "); // split and grab word to array
int length=0;
for(String i:arr){
if("Rama".equals(i)){
System.out.println("Index: "+length);
}
length=length+i.length()+1;// keep length count here
}
You can use the classes Pattern and Matcher. An example when you try to find the word "alpha":
String s = "alpha beta alpha anything";
Pattern p = Pattern.compile("alpha");
Matcher m = p.matcher(s);
while (m.find())
System.out.println(m.start());
It prints: 0, 11
Simply use indexOf() method. This method will let you know if word is in the text by returning index of word otherwise will return -1 means word is not found.
String str = "World is beautiful";
str.indexOf("beautiful"); // This will return value 9 as beautiful word starts at index 9
similarly
str.indexOf("beautifully"); // It will return -1 as this word doesn't exist in the text
Related
I'm trying to create a method that returns the last word in a string but I am having some trouble writing it.
I am trying to do it by finding the last blank space in the string and using a substring to find the word. This is what I have so far:
String strSpace=" ";
int Temp; //the index of the last space
for(int i=str.length()-1; i>0; i--){
if(strSpace.indexOf(str.charAt(i))>=0){
//some code in between that I not sure how to write
}
}
}
I am just beginning in Java so I don't know many of the complicated parts of the language. It would be much appreciated if someone could help me find a simple way to solve this problem. Thanks!
You can do this:
String[] words = originalStr.split(" "); // uses an array
String lastWord = words[words.length - 1];
and you've got your last word.
You are splitting the original string at every space and storing the substrings in an array using the String#split method.
Once you have the array, you are retrieving the last element by taking the value at the last array index (found by taking array length and subtracting 1, since array indices begin at 0).
String str = "Code Wines";
String lastWord = str.substring(str.lastIndexOf(" ")+1);
System.out.print(lastWord);
Output:
Wines
String#lastIndexOf and String#substring are your friends here.
chars in Java can be directly converted to ints, which we'll use to find the last space. Then we'll simply substring from there.
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(phrase.lastIndexOf(' ')));
This prints the space character itself too. To get rid of that, we just increment the index at which we substring by one.
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(1 + phrase.lastIndexOf(' ')));
If you don't want to use String#lastIndexOf, you can loop through the string and substring it at every space until you don't have any left.
String phrase = "The last word of this sentence is stackoverflow";
String subPhrase = phrase;
while(true) {
String temp = subPhrase.substring(1 + subPhrase.indexOf(" "));
if(temp.equals(subPhrase)) {
break;
} else {
subPhrase = temp;
}
}
System.out.println(subPhrase);
You can use: (if you are not familiar with arrays or unusual methods)
public static String lastWord(String a) // only use static if it's in the
main class
{
String lastWord = "";
// below is a new String which is the String without spaces at the ends
String x = a.trim();
for (int i=0; i< x.length(); i++)
{
if (x.charAt(i)==' ')
lastWord = x.substring(i);
}
return lastWord;
}
you just need to traverse the input string from tail when first find blank char stop traverse work and return the word.a simple code like this:
public static String lastWord(String inputs) {
boolean beforWords = false;
StringBuilder sb = new StringBuilder();
for (int i = inputs.length() - 1; i >= 0; i--) {
if (inputs.charAt(i) != ' ') {
sb.append(inputs.charAt(i));
beforWords = true;
} else if (beforWords){
break;
}
}
return sb.reverse().toString();
}
You could try:
System.out.println("Last word of the sentence is : " + string.substring (string.lastIndexOf (' '), string.length()));
Trying to search for patterns of letters in a file, the pattern is entered by a user and comes out as a String, so far I've got it to find the first letter by unsure how to make it test to see if the next letter also matches the pattern.
This is the loop I currently have. any help would be appreciated
public void exactSearch(){
if (pattern==null){UI.println("No pattern");return;}
UI.println("===================\nExact searching for "+patternString);
int j = 0 ;
for(int i=0; i<data.size(); i++){
if(patternString.charAt(i) == data.get(i) )
j++;
UI.println( "found at " + j) ;
}
}
You need to iterate over the first string until you find the first character of the other string. From there, you can create an inner loop and iterate on both simultaneously, like you did.
Hint: be sure to look watch for boundaries as the strings might not be of the same size.
You can try this :-
String a1 = "foo-bar-baz-bar-";
String pattern = "bar";
int foundIndex = 0;
while(foundIndex != -1) {
foundIndex = a1.indexOf(pattern,foundIndex);
if(foundIndex != -1)
{
System.out.println(foundIndex);
foundIndex += 1;
}
}
indexOf - first parameter is the pattern string,
second parameter is starting index from where we have to search.
If pattern is found, it will return the starting index from where the pattern matched.
If pattern is not found, indexOf will return -1.
String data = "foo-bar-baz-bar-";
String pattern = "bar";
int foundIndex = data.indexOf(pattern);
while (foundIndex > -1) {
System.out.println("Match found at: " + foundIndex);
foundIndex = data.indexOf(pattern, foundIndex + pattern.length());
}
Based on your request, you can use this algorithm to search for your positions:
1) We check if we reach at the end of the string, to avoid the invalidIndex error, we verify if the remaining substring's size is smaller than the pattern's length.
2) We calculate the substring at each iteration and we verify the string with the pattern.
List<Integer> positionList = new LinkedList<>();
String inputString = "AAACABCCCABC";
String pattern = "ABC";
for (int i = 0 ; i < inputString.length(); i++) {
if (inputString.length() - i < pattern.length()){
break;
}
String currentSubString = inputString.substring(i, i + pattern.length());
if (currentSubString.equals(pattern)){
positionList.add(i);
}
}
for (Integer pos : positionList) {
System.out.println(pos); // Positions : 4 and 9
}
EDIT :
Maybe it can be optimized, not to use a Collection for this simple task, but I used a LinkedList to write a quicker approach.
I am trying to extract the first letters of each word in a sentence the user has spoken into my app. Currently if the user speaks "Hello World 2015" it inserts that into the text field. I wish to split this so if the user speaks "Hello World 2015" only "HW2015" is inserted into the text field.
final ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
The matches variable is storing the users input in an array.I have looked into using split but not sure exactly how this works.
How would I achieve this?
Thank You
pass this regex and your list into applyRegexToList
it reads:
(get first character) or (any continuous number) or (any character after a space)
(^.{0,1})|(\\d+)|((?<=\\s)[a-zA-z])
()
public static ArrayList<String> applyRegexToList(ArrayList<String> yourList, String regex){
ArrayList<String> matches = new ArrayList<String>();
// Create a Pattern object
Pattern r = Pattern.compile(regex);
for (String sentence:yourList) {
// Now create matcher object.
Matcher m = r.matcher(sentence);
String temp = "";
//while patterns are still being found, concat
while(m.find())
{
temp += m.group(0);
}
matches.add(temp);
}
return matches;
}
You can split a string into an array of string by doing this:
String[] result = my_string.split("\\s+"); // This is a regex for matching spaces
You could then loop over your array, taking the first character of each string:
// The string we'll create
String abbrev = "";
// Loop over the results from the string splitting
for (int i = 0; i < result.length; i++){
// Grab the first character of this entry
char c = result[i].charAt(0);
// If its a number, add the whole number
if (c >= '0' && c <= '9'){
abbrev += result[i];
}
// If its not a number, just append the character
else{
abbrev += c;
}
}
I am trying to use index of to basically print the first letter in a string after each whitespace
I want it to grab the first letter of a persons full name entered to pring back out the intials so if they enterd Billy Bob Joe it would grab BBJ and print it like that I am trying to get it to go from each whitespace +1 to grab the chars.
I cannot use chartAt as I do not know the input the user will give.
I have this code I can get it to go to a certain white space but cannot get it to grab just the first letter after the whitespace it take the whole strign after it
String str ="Billy Joe Bob";
int targetMatch = 1;
int offset = 0;
for(int i = 0 ; i < targetMatch; i++){
int position = str.indexOf(' ',offset);
if(position != -1){
offset = position+1;
}
}
String result = str.substring(offset);
System.out.println(result);
Any help would be appreciated.
String str ="Billy Joe Bob";
int targetMatch = 1;
int offset = 0;
int position = str.indexOf(' ',offset);
String result = "";
result += str.substring(0, 1);
while(position != -1){
position++;
result += str.substring(position,position+1);
position = str.indexOf(' ', position);
}
System.out.println(result);
Try this
Ideally, you'd just split the string on whitespace using String.split. E.g.
String str = "foo bar qux";
for(String tok: str.split("\s+"))
System.out.println(tok.charAt(0));
The easiest solution I can think of is to use String.split.
String str ="Billy Joe Bob";
for (String word : str.split("\s+")) {
if (word.length >= 1) {
System.out.print(word.charAt(0));
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Occurences of substring in a string
As in the subject how to check how many times one string contains another one?
Example:
s1 "babab"
s2 "bab"
Result : 2
If i use Matcher it does only recognize first occurence:
String s1 = JOptionPane.showInputDialog(" ");
String s2 = JOptionPane.showInputDialog(" ");
Pattern p = Pattern.compile(s2);
Matcher m = p.matcher(s1);
int counter = 0;
while(m.find()){
System.out.println(m.group());
counter++;
}
System.out.println(counter);
I can do it like that, but I would like below to use Java libraries iike Scanner, StringTokenizer, Matcher etc:
String s1 = JOptionPane.showInputDialog(" ");
String s2 = JOptionPane.showInputDialog(" ");
String pom;
int count = 0;
for(int i = 0 ; i< s1.length() ; i++){
if(s1.charAt(i) == s2.charAt(0)){
if(i + s2.length() <= s1.length()){
pom = s1.substring(i,i+s2.length());
if(pom.equals(s2)){
count++;
}
}
}
}
System.out.println(count);
One liner solution for the lulz
longStr is the input string. findStr is the string to search for. No assumption, except that longStr and findStr must not be null and findStr must have at least 1 character.
longStr.length() - longStr.replaceAll(Pattern.quote(findStr.substring(0,1)) + "(?=" + Pattern.quote(findStr.substring(1)) + ")", "").length()
Since 2 matches are considered different as long as they starts at different index, and overlapping can happen, we need a way to differentiate between the matches and allow for matched part to be overlapped.
The trick is to consume only the first character of the search string, and use look-ahead to assert the rest of the search string. This allows overlapping portion to be rematched, and by removing the first character of the match, we can count the number of matches.
i think this might work if you know the word you are looking for in the string you might need to edit the regex pattern tho.
String string = "hellohellohellohellohellohello";
Pattern pattern = Pattern.compile("hello");
Matcher matcher = pattern.matcher(string);
int count = 0;
while (matcher.find()) count++;
The class Matcher has two methods "start" and "end" which return the start index and end index of the last match. Further, the method find has an optional parameter "start" at which it starts searching.
you can do it like this
private int counterString(String s,String search) {
int times = 0;
int index = s.indexOf(search,0);
while(index > 0) {
index = s.indexOf(search,index+1);
++times;
}
return times;
}
Some quick Bruce Forte solution:
String someString = "bababab";
String toLookFor = "bab";
int count = 0;
for (int i = 0; i < someString.length(); i++) {
if (someString.length() - i >= toLookFor.length()) {
if (someString.substring(i, i + toLookFor.length()).equals(toLookFor) && !"".equals(toLookFor)) {
count++;
}
}
}
System.out.println(count);
This prints out 3. Please note I assume that none of the Strings is null.