Single character instance from string - java

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.

Related

java.lang.NumberFormatException for input string

I'm creating a program which makes the given input string into number so that input will be coded. But I'm running into a NumberFormatException as soon as the input string gets too long. I can't see how I can fix this.
Note that I have to get substrings from the given string input, turn them into numericValues then get the sum of these two strings as an answer.
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 = "youuu + are = gay"; //as soon as the substrings before = sign are
//longer than 5 characters the exception occurs
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 = 0;
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);
System.out.print(s.toUpperCase(s) +"="+ count + ", ");
}
}
if(words[0].contains(s.toString()))
{
count = count - 1;
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 = Integer.parseInt(first) + Integer.parseInt(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("Yhe s6na maksimaalne pikkus on 18 t2hem2rki ");
}
}
return words;
}
Integers in Java (as in many languages) are limited by a minimum and maximum value.
More information on this can be found here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
You could give a meaningful error in the catch-block
You did not enter a valid 32-bit Integer value.
Or you could switch to something like a BigDecimal which can hold bigger values: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
(watch out: BigDecimal works very different from a normal int, so read the documentation wisely, and Google for examples if necessary)
EDIT: you can parse it to Long as well, if you want that: Long.parseLong(INPUT, 10);. That way you extend the limit to 64-bit.

counting unique words in a string without using an array

So my task is to write a program that counts the number of words and unique words in a given string that we get from the user without using arrays.
I can do the first task and was wondering how I could go about doing the second part.
For counting the number of words in the string I have
boolean increment = false;
for (int i = 0; i < inputPhrase.length(); i++){
if(validChar(inputPhrase.charAt(i))) //validChar(char c) is a simple method that returns a valid character{
increment = true;
}
else if(increment){
phraseWordCount ++;
increment = false;
}
}
if(increment) phraseWordCount++; //in the case the last word is a valid character
(originally i left this out and was off by one word)
to count unique words can I somehow modify this?
Here a suggestion how to do it without arrays:
1) Read every char until a blank is found and add this char to a second String.
2) If a blank is found, add it (or another token to seperate words) to the second String.
2a) Read every word from second String comparing it to the current word from he input String
public static void main(String[] args) {
final String input = "This is a sentence that is containing three times the word is";
final char token = '#';
String processedInput = "";
String currentWord = "";
int wordCount = 0;
int uniqueWordCount = 0;
for (char c : input.toCharArray()) {
if (c != ' ') {
processedInput += c;
currentWord += c;
} else {
processedInput += token;
wordCount++;
String existingWord = "";
int occurences = 0;
for (char c1 : processedInput.toCharArray()) {
if (c1 != token) {
existingWord += c1;
} else {
if (existingWord.equals(currentWord)) {
occurences++;
}
existingWord = "";
}
}
if (occurences <= 1) {
System.out.printf("New word: %s\n", currentWord);
uniqueWordCount++;
}
currentWord = "";
}
}
wordCount++;
System.out.printf("%d words total, %d unique\n", wordCount, uniqueWordCount);
}
Output
New word: This
New word: is
New word: a
New word: sentence
New word: that
New word: containing
New word: three
New word: times
New word: the
New word: word
12 words total, 10 unique
Using the Collections API you can count words with the following method:
private int countWords(final String text) {
Scanner scanner = new Scanner(text);
Set<String> uniqueWords = new HashSet<String>();
while (scanner.hasNext()) {
uniqueWords.add(scanner.next());
}
scanner.close();
return uniqueWords.size();
}
If it is possible that you get normal sentences with punctuation marks you can change the second line to:
Scanner scanner = new Scanner(text.replaceAll("[^0-9a-zA-Z\\s]", "").toLowerCase());
Every time a word ends findUpTo checks if the word is contained in the input before the start of that word. So "if if if" would count as one unique and three total words.
/**
* Created for http://stackoverflow.com/q/22981210/1266906
*/
public class UniqueWords {
public static void main(String[] args) {
String inputPhrase = "one two ones two three one";
countWords(inputPhrase);
}
private static void countWords(String inputPhrase) {
boolean increment = false;
int wordStart = -1;
int phraseWordCount = 0;
int uniqueWordCount = 0;
for (int i = 0; i < inputPhrase.length(); i++){
if(validChar(inputPhrase.charAt(i))) { //validChar(char c) is a simple method that returns a valid character{
increment = true;
if(wordStart == -1) {
wordStart = i;
}
} else if(increment) {
phraseWordCount++;
final String lastWord = inputPhrase.substring(wordStart, i);
boolean unique = findUpTo(lastWord, inputPhrase, wordStart);
if(unique) {
uniqueWordCount++;
}
increment = false;
wordStart = -1;
}
}
if(increment) {
phraseWordCount++; //in the case the last word is a valid character
final String lastWord = inputPhrase.substring(wordStart, inputPhrase.length());
boolean unique = findUpTo(lastWord, inputPhrase, wordStart);
if(unique) {
uniqueWordCount++;
}
}
System.out.println("Words: "+phraseWordCount);
System.out.println("Unique: "+uniqueWordCount);
}
private static boolean findUpTo(String needle, String haystack, int lastPos) {
boolean previousValid = false;
boolean unique = true;
for(int j = 0; unique && j < lastPos - needle.length(); j++) {
final boolean nextValid = validChar(haystack.charAt(j));
if(!previousValid && nextValid) {
// Word start
previousValid = true;
for (int k = 0; k < lastPos - j; k++) {
if(k == needle.length()) {
// We matched all characters. Only if the word isn't finished it is unique
unique = validChar(haystack.charAt(j+k));
break;
}
if (needle.charAt(k) != haystack.charAt(j+k)) {
break;
}
}
} else {
previousValid = nextValid;
}
}
return unique;
}
private static boolean validChar(char c) {
return Character.isAlphabetic(c);
}
}

Count the number of Occurrences of a Word in a String

I am new to Java Strings the problem is that I want to count the Occurrences of a specific word in a String. Suppose that my String is:
i have a male cat. the color of male cat is Black
Now I dont want to split it as well so I want to search for a word that is "male cat". it occurs two times in my string!
What I am trying is:
int c = 0;
for (int j = 0; j < text.length(); j++) {
if (text.contains("male cat")) {
c += 1;
}
}
System.out.println("counter=" + c);
it gives me 46 counter value! So whats the solution?
You can use the following code:
String in = "i have a male cat. the color of male cat is Black";
int i = 0;
Pattern p = Pattern.compile("male cat");
Matcher m = p.matcher( in );
while (m.find()) {
i++;
}
System.out.println(i); // Prints 2
Demo
What it does?
It matches "male cat".
while(m.find())
indicates, do whatever is given inside the loop while m finds a match.
And I'm incrementing the value of i by i++, so obviously, this gives number of male cat a string has got.
If you just want the count of "male cat" then I would just do it like this:
String str = "i have a male cat. the color of male cat is Black";
int c = str.split("male cat").length - 1;
System.out.println(c);
and if you want to make sure that "female cat" is not matched then use \\b word boundaries in the split regex:
int c = str.split("\\bmale cat\\b").length - 1;
StringUtils in apache commons-lang have CountMatches method to counts the number of occurrences of one String in another.
String input = "i have a male cat. the color of male cat is Black";
int occurance = StringUtils.countMatches(input, "male cat");
System.out.println(occurance);
Java 8 version:
public static long countNumberOfOccurrencesOfWordInString(String msg, String target) {
return Arrays.stream(msg.split("[ ,\\.]")).filter(s -> s.equals(target)).count();
}
Java 8 version.
System.out.println(Pattern.compile("\\bmale cat")
.splitAsStream("i have a male cat. the color of male cat is Black")
.count()-1);
This static method does returns the number of occurrences of a string on another string.
/**
* Returns the number of appearances that a string have on another string.
*
* #param source a string to use as source of the match
* #param sentence a string that is a substring of source
* #return the number of occurrences of sentence on source
*/
public static int numberOfOccurrences(String source, String sentence) {
int occurrences = 0;
if (source.contains(sentence)) {
int withSentenceLength = source.length();
int withoutSentenceLength = source.replace(sentence, "").length();
occurrences = (withSentenceLength - withoutSentenceLength) / sentence.length();
}
return occurrences;
}
Tests:
String source = "Hello World!";
numberOfOccurrences(source, "Hello World!"); // 1
numberOfOccurrences(source, "ello W"); // 1
numberOfOccurrences(source, "l"); // 3
numberOfOccurrences(source, "fun"); // 0
numberOfOccurrences(source, "Hello"); // 1
BTW, the method could be written in one line, awful, but it also works :)
public static int numberOfOccurrences(String source, String sentence) {
return (source.contains(sentence)) ? (source.length() - source.replace(sentence, "").length()) / sentence.length() : 0;
}
using indexOf...
public static int count(String string, String substr) {
int i;
int last = 0;
int count = 0;
do {
i = string.indexOf(substr, last);
if (i != -1) count++;
last = i+substr.length();
} while(i != -1);
return count;
}
public static void main (String[] args ){
System.out.println(count("i have a male cat. the color of male cat is Black", "male cat"));
}
That will show: 2
Another implementation for count(), in just 1 line:
public static int count(String string, String substr) {
return (string.length() - string.replaceAll(substr, "").length()) / substr.length() ;
}
Why not recursive ?
public class CatchTheMaleCat {
private static final String MALE_CAT = "male cat";
static int count = 0;
public static void main(String[] arg){
wordCount("i have a male cat. the color of male cat is Black");
System.out.println(count);
}
private static boolean wordCount(String str){
if(str.contains(MALE_CAT)){
count++;
return wordCount(str.substring(str.indexOf(MALE_CAT)+MALE_CAT.length()));
}
else{
return false;
}
}
}
public class TestWordCount {
public static void main(String[] args) {
int count = numberOfOccurences("Alice", "Alice in wonderland. Alice & chinki are classmates. Chinki is better than Alice.occ");
System.out.println("count : "+count);
}
public static int numberOfOccurences(String findWord, String sentence) {
int length = sentence.length();
int lengthWithoutFindWord = sentence.replace(findWord, "").length();
return (length - lengthWithoutFindWord)/findWord.length();
}
}
This will work
int word_count(String text,String key){
int count=0;
while(text.contains(key)){
count++;
text=text.substring(text.indexOf(key)+key.length());
}
return count;
}
Replace the String that needs to be counted with empty string and then use the length without the string to calculate the number of occurrence.
public int occurrencesOf(String word)
{
int length = text.length();
int lenghtofWord = word.length();
int lengthWithoutWord = text.replace(word, "").length();
return (length - lengthWithoutWord) / lenghtofWord ;
}
Once you find the term you need to remove it from String under process so that it won't resolve the same again, use indexOf() and substring() , you don't need to do contains check length times
The string contains that string all the time when looping through it. You don't want to ++ because what this is doing right now is just getting the length of the string if it contains " "male cat"
You need to indexOf() / substring()
Kind of get what i am saying?
If you find the String you are searching for, you can go on for the length of that string (if in case you search aa in aaaa you consider it 2 times).
int c=0;
String found="male cat";
for(int j=0; j<text.length();j++){
if(text.contains(found)){
c+=1;
j+=found.length()-1;
}
}
System.out.println("counter="+c);
This should be a faster non-regex solution.
(note - Not a Java programmer)
String str = "i have a male cat. the color of male cat is Black";
int found = 0;
int oldndx = 0;
int newndx = 0;
while ( (newndx=str.indexOf("male cat", oldndx)) > -1 )
{
found++;
oldndx = newndx+8;
}
There are so many ways for the occurrence of substring and two of theme are:-
public class Test1 {
public static void main(String args[]) {
String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc a ";
count(st, 0, "a".length());
}
public static void count(String trim, int i, int length) {
if (trim.contains("a")) {
trim = trim.substring(trim.indexOf("a") + length);
count(trim, i + 1, length);
} else {
System.out.println(i);
}
}
public static void countMethod2() {
int index = 0, count = 0;
String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
String subString = "my".toLowerCase();
while (index != -1) {
index = inputString.indexOf(subString, index);
if (index != -1) {
count++;
index += subString.length();
}
}
System.out.print(count);
}}
We can count from many ways for the occurrence of substring:-
public class Test1 {
public static void main(String args[]) {
String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc a ";
count(st, 0, "a".length());
}
public static void count(String trim, int i, int length) {
if (trim.contains("a")) {
trim = trim.substring(trim.indexOf("a") + length);
count(trim, i + 1, length);
} else {
System.out.println(i);
}
}
public static void countMethod2() {
int index = 0, count = 0;
String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
String subString = "my".toLowerCase();
while (index != -1) {
index = inputString.indexOf(subString, index);
if (index != -1) {
count++;
index += subString.length();
}
}
System.out.print(count);
}}
I've got another approach here:
String description = "hello india hello india hello hello india hello";
String textToBeCounted = "hello";
// Split description using "hello", which will return
//string array of words other than hello
String[] words = description.split("hello");
// Get number of characters words other than "hello"
int lengthOfNonMatchingWords = 0;
for (String word : words) {
lengthOfNonMatchingWords += word.length();
}
// Following code gets length of `description` - length of all non-matching
// words and divide it by length of word to be counted
System.out.println("Number of matching words are " +
(description.length() - lengthOfNonMatchingWords) / textToBeCounted.length());
Complete Example here,
package com.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class WordsOccurances {
public static void main(String[] args) {
String sentence = "Java can run on many different operating "
+ "systems. This makes Java platform independent.";
String[] words = sentence.split(" ");
Map<String, Integer> wordsMap = new HashMap<String, Integer>();
for (int i = 0; i<words.length; i++ ) {
if (wordsMap.containsKey(words[i])) {
Integer value = wordsMap.get(words[i]);
wordsMap.put(words[i], value + 1);
} else {
wordsMap.put(words[i], 1);
}
}
/*Now iterate the HashMap to display the word with number
of time occurance */
Iterator it = wordsMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> entryKeyValue = (Map.Entry<String, Integer>) it.next();
System.out.println("Word : "+entryKeyValue.getKey()+", Occurance : "
+entryKeyValue.getValue()+" times");
}
}
}
public class WordCount {
public static void main(String[] args) {
// TODO Auto-generated method stub
String scentence = "This is a treeis isis is is is";
String word = "is";
int wordCount = 0;
for(int i =0;i<scentence.length();i++){
if(word.charAt(0) == scentence.charAt(i)){
if(i>0){
if(scentence.charAt(i-1) == ' '){
if(i+word.length()<scentence.length()){
if(scentence.charAt(i+word.length()) != ' '){
continue;}
}
}
else{
continue;
}
}
int count = 1;
for(int j=1 ; j<word.length();j++){
i++;
if(word.charAt(j) != scentence.charAt(i)){
break;
}
else{
count++;
}
}
if(count == word.length()){
wordCount++;
}
}
}
System.out.println("The word "+ word + " was repeated :" + wordCount);
}
}
Simple solution is here-
Below code uses HashMap as it will maintain keys and values. so here keys will be word and values will be count (occurance of a word in a given string).
public class WordOccurance
{
public static void main(String[] args)
{
HashMap<String, Integer> hm = new HashMap<>();
String str = "avinash pande avinash pande avinash";
//split the word with white space
String words[] = str.split(" ");
for (String word : words)
{
//If already added/present in hashmap then increment the count by 1
if(hm.containsKey(word))
{
hm.put(word, hm.get(word)+1);
}
else //if not added earlier then add with count 1
{
hm.put(word, 1);
}
}
//Iterate over the hashmap
Set<Entry<String, Integer>> entry = hm.entrySet();
for (Entry<String, Integer> entry2 : entry)
{
System.out.println(entry2.getKey() + " "+entry2.getValue());
}
}
}
public int occurrencesOf(String word) {
int length = text.length();
int lenghtofWord = word.length();
int lengthWithoutWord = text.replaceAll(word, "").length();
return (length - lengthWithoutWord) / lenghtofWord ;
}
for scala it's just 1 line
def numTimesOccurrenced(text:String, word:String) =text.split(word).size-1

Write a method to print a string with words reversed, without the use of any standard functions [duplicate]

This question already has answers here:
Printing reverse of any String without using any predefined function?
(34 answers)
Closed 8 years ago.
I was asked this in a technical interview. I have no idea whatsoever please please help me.
it goes in infinite loop. I just cant find the correct logic.
not once, but twice i came across this kind of a question, so please help
public static int numberOfCharsInString(String sentence)
{
int numberOfChars = 0,i=0;
while (!sentence.equals(""))
{
sentence = sentence.substring(1);
++numberOfChars;
}
return numberOfChars;
}
public static void reverseSequenceOfWords(String inp)
{
int len=numberOfCharsInString(inp);
char[] in=inp.toCharArray();
int i=0;
for(i=len-1;i>=0;i--)
{
if(in[i]==' ')
{
while(!in.equals("")||in.equals(" "))
{
System.out.print(in[i]+" ");
}
}
else if(in[i]=='\0')
{
break;
}
}
}
public static void main(String[] args)
{
int length=0;
String inpstring = "";
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
try
{
System.out.print("Enter a string to reverse:");
inpstring = reader.readLine();
length=numberOfCharsInString(inpstring);
System.out.println("Number of Characters: "+length);
reverseSequenceOfWords(inpstring);
}
catch (Exception e)
{
e.printStackTrace();
}
}
String[] array = "Are you crazy".split(" ");
for (int i = array.length - 1; i >= 0; --i) {
System.out.print(array[i] + " ");
}
Brute forced this so hard lol
public static void main (String args[]){
String input = new Scanner(System.in).nextLine();
input+=" ";
ArrayList<String> words = new ArrayList<String>();
int start = 0;
for(int i=0; i<input.length(); i++){
if(input.charAt(i)==' '){
String toAdd="";
for(int r=start; r<i; r++){
toAdd+=input.charAt(r);
}
words.add(toAdd);
start = i+1;
}
}
for(int i=words.size()-1; i>=0; i--){
System.out.print(words.get(i)+" ");
}
}
I've used String.length() and String.substring()and String.charAt() - I hope that is allowed.
private static class Word {
private final String message;
private final int start;
private final int end;
public Word(String message, int start, int end) {
this.message = message;
this.start = start;
this.end = end;
}
#Override
public String toString() {
return message.substring(start, end);
}
}
private Word[] split(String message) {
// Split it into words - there cannot be more words than characters in the message.
int[] spaces = new int[message.length()];
// How many words.
int nWords = 0;
// Pretend there's a space at the start.
spaces[0] = -1;
// Walk the message.
for (int i = 0; i < message.length(); i++) {
if (message.charAt(i) == ' ') {
spaces[++nWords] = i;
}
}
// Record the final position.
spaces[++nWords] = message.length();
// Build the word array.
Word[] words = new Word[nWords];
for (int i = 0; i < nWords; i++) {
words[i] = new Word(message, spaces[i] + 1, spaces[i + 1]);
}
return words;
}
private String reverse(String message) {
Word[] split = split(message);
String reversed = "";
for ( int i = split.length - 1; i >= 0; i--) {
reversed += split[i].toString();
if ( i > 0 ) {
reversed += " ";
}
}
return reversed;
}
public void test() {
String message = "Hello how are you today?";
System.out.println(reverse(message));
}
prints
today? you are how Hello
Much more minimal but less useful. Only uses length, charAt and substring again:
public void printWordsReversed(String message) {
int end = message.length();
for ( int i = end - 1; i >= 0; i--) {
if ( message.charAt(i) == ' ') {
System.out.print(message.substring(i+1, end)+" ");
end = i;
}
}
System.out.print(message.substring(0, end));
}
The only function i'm still using is the IndexOf function, but that is not that hard to create for yourself.
static void Main(string[] args)
{
string sentence = "are you cracy";
int length = Program.StringLength(sentence);
int currentpos = 0;
List<string> wordList = new List<string>();
int wordCount = 0;
while (currentpos < length)
{
// find the next space
int spacepos = sentence.IndexOf(' ', currentpos);
string word;
if (spacepos < 0)
{
// end of string reached.
word = sentence.Substring(currentpos, length - currentpos);
wordList.Add(word);
wordCount++;
// no need to continue.
break;
}
word = sentence.Substring(currentpos, spacepos - currentpos);
wordList.Add(word);
wordCount++;
currentpos = spacepos + 1;
}
// display
for (int i = wordList.Count - 1; i >= 0; i--)
{
// after first word is display, add spaces to the output
if (i < wordList.Count - 1)
{
Console.WriteLine(" ");
}
// display word
Console.WriteLine(wordList[i]);
}
}
public static int StringLength(String sentence)
{
int numberOfChars = 0;
while (!sentence.Equals(""))
{
sentence = sentence.Substring(1);
++numberOfChars;
}
return numberOfChars;
}

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