How to handle: java.lang.ArrayIndexOutOfBoundsException: 1 - java

I have a program that takes in a file of unindented code and comments the program takes the specified file and will output an indented version of the code.
I keep on getting the java.lang.ArrayIndexOutOfBoundsException: 1 error. This seems to occur when I have only one comment on a line as for when it splits the string the index only takes up 0. I have got an if statement in place to handle a comment on a line on its own but it still throws the exception.
Would I need to implement an if statement to check whether or not the split string has more than 1 part to it?
import java.io.*;
import java.util.*;
class Program
{
public static int spaces = 0;
public static int longestLine = 0;
public static int commentSpaces;
public static String beforeComment;
public static String afterComment;
public static void main(String args[]) throws FileNotFoundException
{
Scanner input2 = new Scanner(new File("C:\\Users\\James\\Music\\code.java")); //get text from file
while (input2.hasNextLine() == true) { //get the longest line
String text = input2.nextLine();
if (text.contains("//")) {
if (text.contains("\"//")) {
printLine(text);
}
String[] parts = text.split("//");
String codeOnly = parts[0];
if (codeOnly.length() > longestLine) {
longestLine = codeOnly.length();
}
}
else {
if (text.length() > longestLine) {
longestLine = text.length();
}
}
if (input2.hasNextLine() == false) {
break;
}
}
Scanner input3 = new Scanner(new File("C:\\Users\\James\\Music\\code.java"));
while (input3.hasNextLine()) { //indent comments
String text = input3.nextLine();
if (text.contains("}")) {
spaces -=2;
}
for (int i = 0; i < spaces; i++) {
System.out.print(" ");
}
if (text.startsWith("//")){
String justComment = text;
commentSpaces = longestLine - spaces + 6;
for (int i = 0; i < commentSpaces; i++) {
System.out.print(" ");
}
printLine(justComment);
System.out.println(" ");
}
if (text.contains("\"//")) {
printLine(text);
}
if (text.contains("//")) {
String[] parts = text.split("(?=//)");
beforeComment = parts[0].trim(); // trim() to get rid of any spaces that are already present within the code
afterComment = parts[1];
printLine(beforeComment);
commentSpaces = longestLine - beforeComment.length() - spaces + 5;
for (int i = 0; i < commentSpaces; i++) {
System.out.print(" ");
}
printLine(afterComment);
System.out.println();
}
else {
printLine(text);
System.out.println();
}
if (text.contains("{")) {
spaces +=2;
}
}
}
public static void printLine(String text) {
Scanner data = new Scanner(text);
while (data.hasNext()) {
System.out.print(" " + data.next());
}
}
public static void yesItContains() {
System.out.print("It contains a string");
System.exit(0);
}
}

I think that if text is "something//" meaning it is ending in a empty comment your parts will only have length 1. So yes, you need to check it, e.g. via afterComment = parts.length > 1 ? parts[1] : "";. Note that lines like "something // something else // blabla" might break that logic as well.

Related

How to read an empty string to create output

I have file of which I need to read input. On one of the lines, there is no name added. In this case, I want to print out that no match was found. The problem that I'm having is that I don't know how I can make sure the program actually reads the part as an empty string. What happens now is that the will just leave the line empty on the console.
The date input looks like this:
5=20=22=10=2=0=0=1=0=1;Vincent Appel,Johannes Mondriaan
2=30=15=8=4=3=2=0=0=0;
class Administration {
public static final int TOTAL_NUMBER_OF_SIMULARITY_SCORES = 10;
public static final String ZERO_MATCHES = "_";
public static final String LESS_THAN_TWENTY_MATCHES= "-";
public static final String TWENTY_OR_MORE_MATCHES = "^";
PrintStream out;
Administration() {
out = new PrintStream(System.out);
}
void printSimilarityScores (Scanner similarityScoresScanner, String similarityScoresInput) {
similarityScoresScanner.useDelimiter("=|;");
int length = similarityScoresInput.length();
for (int i = 0; i < TOTAL_NUMBER_OF_SIMULARITY_SCORES; i++) {
int grade = similarityScoresScanner.nextInt();
if (grade == 0) {
out.printf(ZERO_MATCHES);
} else if (grade < 20) {
out.printf(LESS_THAN_TWENTY_MATCHES);
} else {
out.printf(TWENTY_OR_MORE_MATCHES);
}
}
System.out.print("\n");
similarityScoresScanner.useDelimiter(";|,");
while(similarityScoresScanner.hasNext()) {
String name = similarityScoresScanner.next();
if (length < 22) {
out.printf("No matches found\n");
} else {
System.out.print("\n" + name);
}
}
}
void start() {
Scanner fileScanner = UIAuxiliaryMethods.askUserForInput().getScanner();
while (fileScanner.hasNext()) {
String finalGradeInput = fileScanner.nextLine();
String similarityScoresInput = fileScanner.nextLine();
Scanner finalGradeInputScanner = new Scanner(finalGradeInput);
Scanner similarityScoresScanner = new Scanner(similarityScoresInput);
printFinalGrade(finalGradeInputScanner);
printSimilarityScores(similarityScoresScanner, similarityScoresInput);
}
}
public static void main(String[] argv) {
new Administration().start();
}
}
An easier solution would be to read the file, line by line and handle them like this :
split by the separator
check if there is more than 1 element,
if positive print them
Scanner similarityScoresScanner = new Scanner(myFile);
while (similarityScoresScanner.hasNextLine()) {
String[] content = similarityScoresScanner.nextLine().split("[;,]");
if (content.length == 1) {
System.out.println("No matches found");
} else {
for (int i = 1; i < content.length; i++) {
System.out.println(content[i]);
}
}
}

How do I get my output to contain the spaces I need?

I have to capitalize the first letter in every word passed into the string. My output is doing that capitalization, but it's not maintaining the format of the original output. For example, string input is "hello world", my output is "HelloWorld", and my desired output should be "Hello World."
I've tried to add spaces where I can throughout the code but nothing works. I think the problem is that when I use toCharArray, it gives me an output with no spaces? So my concatenation result is adding everything in one swoop, versus each word separately?
Or I thought that my code was using string concatenation with my result, and it's not being separated because I have both words going into the same variable.
import java.util.*;
import java.io.*;
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
String result = "";
for(int i = 0; i < word.length; i++) {
char[] charWord = word[i].toCharArray();
for(int j = 0; j < charWord.length; j++ ) {
String cap = word[i].charAt(0) + "";
cap = cap.toUpperCase();
//System.out.print(" ");
result += (j == 0 ? cap : word[i].charAt(j));
}
}
return result;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}
No errors. Just not getting desired output.
When you did String[] word = str.split(" ");, the space between each word is taken out and you are now left with only the words in an array. You should use String.join(" ", word) on the resultant words array to reverse the effects so you get the spaces back.
Instead of going through each word char by char, try this:
for(int i = 0; i < word.length; i++) {
word[i] = word[i].substring(0, 1).toUpperCase() + word[i].substring(1);
}
result = String.join(" ", word);
Try this:
import java.util.*;
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
String result = "";
for(int i = 0; i < word.length; i++) {
result += capitalize(word[i]) + (i != word.length - 1 ? " " : "");
}
return result;
}
private static String capitalize(String s){
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}
You can use the below code.
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
StringBuilder result = new StringBuilder();
for (int i = 0; i < word.length; i++) {
char[] charWord = word[i].toCharArray();
for (int j = 0; j < charWord.length; j++) {
String cap = word[i].charAt(0) + "";
cap = cap.toUpperCase();
//System.out.print(" ");
result.append(j == 0 ? cap : word[i].charAt(j));
}
result.append(" ");
}
return result.toString();
}
public static void main(String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}

Single character instance from string

i was wondering how can i create a method where i can get the single instance from a string and give it a numericValue for example, if theres a String a = "Hello what the hell" there are 4 l characters and i want to give a substring from the String a which is Hello and give it numeric values. Right now in my program it gets all the character instances from string so the substring hello would get number values from the substring hell too because it also has the same characters.
my code :
public class Puzzle {
private static char[] letters = {'a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z'};
private static String input;
private static String delimiters = "\\s+|\\+|//+|=";
public static void main(String[]args)
{
input = "help + me = please";
System.out.println(putValues(input));
}
//method to put numeric values for substring from input
#SuppressWarnings("static-access")
public static long putValues(String input)
{
Integer count;
long answer = 0;
String first="";
String second = "";
StringBuffer sb = new StringBuffer(input);
int wordCounter = Countwords();
String[] words = countLetters();
System.out.println(input);
if(input.isEmpty())
{
System.out.println("Sisestage mingi s6na");
}
if(wordCounter == -1 ||countLetters().length < 1){
return -1;
}
for(Character s : input.toCharArray())
{
for(Character c : letters)
{
if(s.equals(c))
{
count = c.getNumericValue(c) - 9;
System.out.print(s.toUpperCase(s) +"="+ count + ", ");
}
}
if(words[0].contains(s.toString()))
{
count = s.getNumericValue(s);
//System.out.println(count);
first += count.toString();
}
if(words[3].contains(s.toString())){
count = s.getNumericValue(s);
second += count.toString();
}
}
try {
answer = Long.parseLong(first)+ Long.parseLong(second);
} catch(NumberFormatException ex)
{
System.out.println(ex);
}
System.out.println("\n" + first + " + " + second + " = " + answer);
return answer;
}
public static int Countwords()
{
String[] countWords = input.split(" ");
int counter = countWords.length - 2;
if(counter == 0) {
System.out.println("Sisend puudu!");
return -1;
}
if(counter > 1 && counter < 3) {
System.out.println("3 sõna peab olema");
return -1;
}
if(counter > 3) {
System.out.println("3 sõna max!");
return -1;
}
return counter;
}
//method which splits input String and returns it as an Array so i can put numeric values after in the
//putValue method
public static String[] countLetters()
{
int counter = 0;
String[] words = input.split(delimiters);
for(int i = 0; i < words.length;i++) {
counter = words[i].length();
if(words[i].length() > 18) {
System.out.println("One word can only be less than 18 chars");
}
}
return words;
}
Program has to solve the word puzzles where you have to guess which digit corresponds to which letter to make a given equality valid. Each letter must correspond to a different decimal digit, and leading zeros are not allowed in the numbers.
For example, the puzzle SEND+MORE=MONEY has exactly one solution: S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2, giving 9567+1085=10652.
import java.util.ArrayList;
public class main {
private static String ChangeString;
private static String[] ArrayA;
private static String a;
private static int wordnumber;
private static String temp;
public static void main(String[] args) {
// TODO Auto-generated method stub
a = "hello what the hell";
wordnumber = 0;
identifyint(a,wordnumber);
}
public static void identifyint (String a, int WhichWord){
ChangeString = a.split(" ")[WhichWord];
ArrayA = a.split(" ");
replaceword();
ArrayA[wordnumber] = ChangeString;
//System.out.print(ArrayA[wordnumber]);
a = "";
for(int i = 0; i<ArrayA.length;i++){
if(i==wordnumber){
a = a.concat(temp+ " ");
}
else{
a = a.concat(ArrayA[i]+" ");
}
}
System.out.print(a);
}
public static void replaceword(){
temp = "";
Character arr[] = new Character[ChangeString.length()];
for(int i = 0; i<ChangeString.length();i++){
arr[i] = ChangeString.charAt(i);
Integer k = arr[i].getNumericValue(arr[i])-9;
temp = temp.concat(""+k);
}
a = temp;
}
}
Change wordnumber to the word you want to replace each time. If this is not what you have asked for, please explain your question in more detail.

How to remove duplicate character from a string in java?

In my program, the user enters a string, and it first finds the largest mode of characters in the string. Next, my program is supposed to remove all duplicates of a character in a string, (user input: aabc, program prints: abc) which I'm not entirely certain on how to do. I can get it to remove duplicates from some strings, but not all. For example, when the user puts "aabc" it will print "abc", but if the user puts "aabbhh", it will print "abbhh." Also, before I added the removeDup method to my program, it would only print the maxMode once, but after I added the removeDup method, it began to print the maxMode twice. How do I keep it from printing it twice?
Note: I cannot convert the strings to an array.
import java.util.Scanner;
public class JavaApplication3 {
static class MyStrings {
String s;
void setMyStrings(String str) {
s = str;
}
int getMode() {
int i;
int j;
int count = 0;
int maxMode = 0, maxCount = 1;
for (i = 0; i< s.length(); i++) {
maxCount = count;
count = 0;
for (j = s.length()-1; j >= 0; j--) {
if (s.charAt(j) == s.charAt(i))
count++;
if (count > maxCount){
maxCount = count;
maxMode = i;
}
}
}
System.out.println(s.charAt(maxMode)+" = largest mode");
return maxMode;
}
String removeDup() {
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = 0; j < rdup.length(); j++) {
if (s.charAt(i) == s.charAt(j)){
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
System.out.print(rdup);
System.out.println();
return rdup;
}
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
MyStrings setS = new MyStrings();
String s;
System.out.print("Enter string:");
s = in.nextLine();
setS.setMyStrings(s);
setS.getMode();
setS.removeDup();
}
}
Try this method...should work fine!
String removeDup()
{
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = i+1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
// System.out.print(rdup);
System.out.println();
return rdup;
}
Welcome to StackOverflow!
You're calling getMode() both outside and inside of removeDup(), which is why it's printing it twice.
In order to remove all duplicates, you'll have to call removeDup() over and over until all the duplicates are gone from your string. Right now you're only calling it once.
How might you do that? Think about how you're detecting duplicates, and use that as the end condition for a while loop or similar.
Happy coding!
Shouldn't this be an easier way? Also, i'm still learning.
import java.util.*;
public class First {
public static void main(String arg[])
{
Scanner sc= new Scanner(System.in);
StringBuilder s=new StringBuilder(sc.nextLine());
//String s=new String();
for(int i=0;i<s.length();i++){
String a=s.substring(i, i+1);
while(s.indexOf(a)!=s.lastIndexOf(a)){s.deleteCharAt(s.lastIndexOf(a));}
}
System.out.println(s.toString());
}
}
You can do this:
public static void main(String[] args) {
String str = new String("PINEAPPLE");
Set <Character> letters = new <Character>HashSet();
for (int i = 0; i < str.length(); i++) {
letters.add(str.charAt(i));
}
System.out.println(letters);
}
I think an optimized version which supports ASCII codes can be like this:
public static void main(String[] args) {
System.out.println(removeDups("*PqQpa abbBBaaAAzzK zUyz112235KKIIppP!!QpP^^*Www5W38".toCharArray()));
}
public static String removeDups(char []input){
long ocr1=0l,ocr2=0l,ocr3=0;
int index=0;
for(int i=0;i<input.length;i++){
int val=input[i]-(char)0;
long ocr=val<126?val<63?ocr1:ocr2:ocr3;
if((ocr& (1l<<val))==0){//not duplicate
input[index]=input[i];
index++;
}
if(val<63)
ocr1|=(1l<<val);
else if(val<126)
ocr2|=(1l<<val);
else
ocr3|=(1l<<val);
}
return new String(input,0,index);
}
please keep in mind that each of orc(s) represent a mapping of a range of ASCII characters and each java long variable can grow as big as (2^63) and since we have 128 characters in ASCII so we need three ocr(s) which basically maps the occurrences of the character to a long number.
ocr1: (char)0 to (char)62
ocr2: (char)63 to (char)125
ocr3: (char)126 to (char)128
Now if a duplicate was found the
(ocr& (1l<<val))
will be greater than zero and we skip that char and finally we can create a new string with the size of index which shows last non duplicate items index.
You can define more orc(s) and support other character-sets if you want.
Can use HashSet as well as normal for loops:
public class RemoveDupliBuffer
{
public static String checkDuplicateNoHash(String myStr)
{
if(myStr == null)
return null;
if(myStr.length() <= 1)
return myStr;
char[] myStrChar = myStr.toCharArray();
HashSet myHash = new HashSet(myStrChar.length);
myStr = "";
for(int i=0; i < myStrChar.length ; i++)
{
if(! myHash.add(myStrChar[i]))
{
}else{
myStr += myStrChar[i];
}
}
return myStr;
}
public static String checkDuplicateNo(String myStr)
{
// null check
if (myStr == null)
return null;
if (myStr.length() <= 1)
return myStr;
char[] myChar = myStr.toCharArray();
myStr = "";
int tail = 0;
int j = 0;
for (int i = 0; i < myChar.length; i++)
{
for (j = 0; j < tail; j++)
{
if (myChar[i] == myChar[j])
{
break;
}
}
if (j == tail)
{
myStr += myChar[i];
tail++;
}
}
return myStr;
}
public static void main(String[] args) {
String myStr = "This is your String";
myStr = checkDuplicateNo(myStr);
System.out.println(myStr);
}
Try this simple answer- works well for simple character string accepted as user input:
import java.util.Scanner;
public class string_duplicate_char {
String final_string = "";
public void inputString() {
//accept string input from user
Scanner user_input = new Scanner(System.in);
System.out.println("Enter a String to remove duplicate Characters : \t");
String input = user_input.next();
user_input.close();
//convert string to char array
char[] StringArray = input.toCharArray();
int StringArray_length = StringArray.length;
if (StringArray_length < 2) {
System.out.println("\nThe string with no duplicates is: "
+ StringArray[1] + "\n");
} else {
//iterate over all elements in the array
for (int i = 0; i < StringArray_length; i++) {
for (int j = i + 1; j < StringArray_length; j++) {
if (StringArray[i] == StringArray[j]) {
int temp = j;//set duplicate element index
//delete the duplicate element by copying the adjacent elements by one place
for (int k = temp; k < StringArray_length - 1; k++) {
StringArray[k] = StringArray[k + 1];
}
j++;
StringArray_length--;//reduce char array length
}
}
}
}
System.out.println("\nThe string with no duplicates is: \t");
//print the resultant string with no duplicates
for (int x = 0; x < StringArray_length; x++) {
String temp= new StringBuilder().append(StringArray[x]).toString();
final_string=final_string+temp;
}
System.out.println(final_string);
}
public static void main(String args[]) {
string_duplicate_char object = new string_duplicate_char();
object.inputString();
}
}
Another easy solution to clip the duplicate elements in a string using HashSet and ArrayList :
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class sample_work {
public static void main(String args[]) {
String input = "";
System.out.println("Enter string to remove duplicates: \t");
Scanner in = new Scanner(System.in);
input = in.next();
in.close();
ArrayList<Character> String_array = new ArrayList<Character>();
for (char element : input.toCharArray()) {
String_array.add(element);
}
HashSet<Character> charset = new HashSet<Character>();
int array_len = String_array.size();
System.out.println("\nLength of array = " + array_len);
if (String_array != null && array_len > 0) {
Iterator<Character> itr = String_array.iterator();
while (itr.hasNext()) {
Character c = (Character) itr.next();
if (charset.add(c)) {
} else {
itr.remove();
array_len--;
}
}
}
System.out.println("\nThe new string with no duplicates: \t");
for (int i = 0; i < array_len; i++) {
System.out.println(String_array.get(i).toString());
}
}
}
your can use this simple code and understand how to remove duplicates values from string.I think this is the simplest way to understand this problem.
class RemoveDup
{
static int l;
public String dup(String str)
{
l=str.length();
System.out.println("length"+l);
char[] c=str.toCharArray();
for(int i=0;i<l;i++)
{
for(int j=0;j<l;j++)
{
if(i!=j)
{
if(c[i]==c[j])
{
l--;
for(int k=j;k<l;k++)
{
c[k]=c[k+1];
}
j--;
}
}
}
}
System.out.println("after concatination lenght:"+l);
StringBuilder sd=new StringBuilder();
for(int i=0;i<l;i++)
{
sd.append(c[i]);
}
str=sd.toString();
return str;
}
public static void main(String[] ar)
{
RemoveDup obj=new RemoveDup();
Scanner sc=new Scanner(System.in);
String st,t;
System.out.println("enter name:");
st=sc.nextLine();
sc.close();
t=obj.dup(st);
System.out.println(t);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication26;
import java.util.*;
/**
*
* #author THENNARASU
*/
public class JavaApplication26 {
public static void main(String[] args) {
int i,j,k=0,count=0,m;
char a[]=new char[10];
char b[]=new char[10];
Scanner ob=new Scanner(System.in);
String str;
str=ob.next();
a=str.toCharArray();
int c=str.length();
for(j=0;j<c;j++)
{
for(i=0;i<j;i++)
{
if(a[i]==a[j])
{
count=1;
}
}
if(count==0)
{
b[k++]=a[i];
}
count=0;
}
for(m=0;b[m]!='\0';m++)
{
System.out.println(b[m]);
}
}
}
i wrote this program. Am using 2 char arrays instead. You can define the number of duplicate chars you want to eliminate from the original string and also shows the number of occurances of each character in the string.
public String removeMultipleOcuranceOfChar(String string, int numberOfChars){
char[] word1 = string.toCharArray();
char[] word2 = string.toCharArray();
int count=0;
StringBuilder builderNoDups = new StringBuilder();
StringBuilder builderDups = new StringBuilder();
for(char x: word1){
for(char y : word2){
if (x==y){
count++;
}//end if
}//end inner loop
System.out.println(x + " occurance: " + count );
if (count ==numberOfChars){
builderNoDups.append(x);
}else{
builderDups.append(x);
}//end if else
count = 0;
}//end outer loop
return String.format("Number of identical chars to be in or out of input string: "
+ "%d\nOriginal word: %s\nWith only %d identical chars: %s\n"
+ "without %d identical chars: %s",
numberOfChars,string,numberOfChars, builderNoDups.toString(),numberOfChars,builderDups.toString());
}
Try this simple solution for REMOVING DUPLICATE CHARACTERS/LETTERS FROM GIVEN STRING
import java.util.Scanner;
public class RemoveDuplicateLetters {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("enter a String:");
String s=scn.nextLine();
String ans="";
while(s.length()>0)
{
char ch = s.charAt(0);
ans+= ch;
s = s.replace(ch+"",""); //Replacing all occurrence of the current character by a spaces
}
System.out.println("after removing all duplicate letters:"+ans);
}
}
In Java 8 we can do that using
private void removeduplicatecharactersfromstring() {
String myString = "aabcd eeffff ghjkjkl";
StringBuilder builder = new StringBuilder();
Arrays.asList(myString.split(" "))
.forEach(s -> {
builder.append(Stream.of(s.split(""))
.distinct().collect(Collectors.joining()).concat(" "));
});
System.out.println(builder); // abcd ef ghjkl
}

Java: method to get position of a match in a String?

String match = "hello";
String text = "0123456789hello0123456789";
int position = getPosition(match, text); // should be 10, is there such a method?
The family of methods that does this are:
int indexOf(String str)
indexOf(String str, int fromIndex)
int lastIndexOf(String str)
lastIndexOf(String str, int fromIndex)
Returns the index within this string of the first (or last) occurrence of the specified substring [searching forward (or backward) starting at the specified index].
String text = "0123hello9012hello8901hello7890";
String word = "hello";
System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"
// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
System.out.println(i);
} // prints "4", "13", "22"
// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
System.out.println(i);
} // prints "22", "13", "4"
This works using regex.
String text = "I love you so much";
String wordToFind = "love";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
while (match.find()) {
System.out.println("Found love at index "+ match.start() +" - "+ (match.end()-1));
}
Output :
Found 'love' at index 2 - 5
General Rule :
Regex search left to right, and once the match characters has been used, it cannot be reused.
text.indexOf(match);
See the String javadoc
Finding a single index
As others have said, use text.indexOf(match) to find a single match.
String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10
Finding multiple indexes
Because of #StephenC's comment about code maintainability and my own difficulty in understanding #polygenelubricants' answer, I wanted to find another way to get all the indexes of a match in a text string. The following code (which is modified from this answer) does so:
String text = "0123hello9012hello8901hello7890";
String match = "hello";
int index = text.indexOf(match);
int matchLength = match.length();
while (index >= 0) { // indexOf returns -1 if no match found
System.out.println(index);
index = text.indexOf(match, index + matchLength);
}
You can get all matches in a file simply by assigning inside while-loop, cool:
$ javac MatchTest.java
$ java MatchTest
1
16
31
46
$ cat MatchTest.java
import java.util.*;
import java.io.*;
public class MatchTest {
public static void main(String[] args){
String match = "hello";
String text = "hello0123456789hello0123456789hello1234567890hello3423243423232";
int i =0;
while((i=(text.indexOf(match,i)+1))>0)
System.out.println(i);
}
}
int match_position=text.indexOf(match);
import java.util.StringTokenizer;
public class Occourence {
public static void main(String[] args) {
String key=null,str ="my name noorus my name noorus";
int i=0,tot=0;
StringTokenizer st=new StringTokenizer(str," ");
while(st.hasMoreTokens())
{
tot=tot+1;
key = st.nextToken();
while((i=(str.indexOf(key,i)+1))>0)
{
System.out.println("position of "+key+" "+"is "+(i-1));
}
}
System.out.println("total words present in string "+tot);
}
}
I have some big code but working nicely....
class strDemo
{
public static void main(String args[])
{
String s1=new String("The Ghost of The Arabean Sea");
String s2=new String ("The");
String s6=new String ("ehT");
StringBuffer s3;
StringBuffer s4=new StringBuffer(s1);
StringBuffer s5=new StringBuffer(s2);
char c1[]=new char[30];
char c2[]=new char[5];
char c3[]=new char[5];
s1.getChars(0,28,c1,0);
s2.getChars(0,3,c2,0);
s6.getChars(0,3,c3,0); s3=s4.reverse();
int pf=0,pl=0;
char c5[]=new char[30];
s3.getChars(0,28,c5,0);
for(int i=0;i<(s1.length()-s2.length());i++)
{
int j=0;
if(pf<=1)
{
while (c1[i+j]==c2[j] && j<=s2.length())
{
j++;
System.out.println(s2.length()+" "+j);
if(j>=s2.length())
{
System.out.println("first match of(The) :->"+i);
}
pf=pf+1;
}
}
}
for(int i=0;i<(s3.length()-s6.length()+1);i++)
{
int j=0;
if(pl<=1)
{
while (c5[i+j]==c3[j] && j<=s6.length())
{
j++;
System.out.println(s6.length()+" "+j);
if(j>=s6.length())
{
System.out.println((s3.length()-i-3));
pl=pl+1;
}
}
}
}
}
}
//finding a particular word any where inthe string and printing its index and occurence
class IndOc
{
public static void main(String[] args)
{
String s="this is hyderabad city and this is";
System.out.println("the given string is ");
System.out.println("----------"+s);
char ch[]=s.toCharArray();
System.out.println(" ----word is found at ");
int j=0,noc=0;
for(int i=0;i<ch.length;i++)
{
j=i;
if(ch[i]=='i' && ch[j+1]=='s')
{
System.out.println(" index "+i);
noc++;
}
}
System.out.println("----- no of occurences are "+noc);
}
}
String match = "hello";
String text = "0123456789hello0123456789hello";
int j = 0;
String indxOfmatch = "";
for (int i = -1; i < text.length()+1; i++) {
j = text.indexOf("hello", i);
if (i>=j && j > -1) {
indxOfmatch += text.indexOf("hello", i)+" ";
}
}
System.out.println(indxOfmatch);
If you're going to scan for 'n' matches of the search string, I'd recommend using regular expressions.
They have a steep learning curve, but they'll save you hours when it comes to complex searches.
for multiple occurrence and the character found in string??yes or no
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SubStringtest {
public static void main(String[] args)throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the string");
String str=br.readLine();
System.out.println("enter the character which you want");
CharSequence ch=br.readLine();
boolean bool=str.contains(ch);
System.out.println("the character found is " +bool);
int position=str.indexOf(ch.toString());
while(position>=0){
System.out.println("the index no of character is " +position);
position=str.indexOf(ch.toString(),position+1);
}
}
}
public int NumberWordsInText(String FullText_, String WordToFind_, int[] positions_)
{
int iii1=0;
int iii2=0;
int iii3=0;
while((iii1=(FullText_.indexOf(WordToFind_,iii1)+1))>0){iii2=iii2+1;}
// iii2 is the number of the occurences
if(iii2>0) {
positions_ = new int[iii2];
while ((iii1 = (FullText_.indexOf(WordToFind_, iii1) + 1)) > 0) {
positions_[iii3] = iii1-1;
iii3 = iii3 + 1;
System.out.println("position=" + positions_[iii3 - 1]);
}
}
return iii2;
}
class Main{
public static int string(String str, String str1){
for (int i = 0; i <= str.length() - str1.length(); i++){
int j;
for (j = 0; j < str1.length(); j++) {
if (str1.charAt(j) != str.charAt(i + j)) {
break;
}
}
if (j == str1.length()) {
return i;
}}
return -1;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String str=sc.nextLine();
System.out.println("Enter the Substring");
String str1=sc.nextLine();
System.out.println("The position of the Substring is "+string(str, str1));
}
}

Categories