How can i get the # of times a single word is in a given sentence.. String.split cannot be used.. I don't really need the code. I just need an idea to get started..
package exam2;
import java.util.Arrays;
public class Problem2 {
/**
* #param args
*/
public static String input, word, a, b, c;
public static int index;
public static void Input() {
System.out.println("Enter Sentence: ");
input = IO.readString();
System.out.println("Enter Word: ");
word = IO.readString();
}
public static void Calc() {
Input();
index = input.indexOf(word);
int[] data = new int[input.length()];
data[0] = index;
while (index >= 0) {
System.out.println("Index : " + index);
for (int i = 1; i < data.length; i++) {
data[i] = index;
}
index = input.indexOf(word, index + word.length());
}
int count = 0;
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data.length; j++) {
if (data[i] == data[j]) {
a = input.substring(data[i], data[i] + word.length());
}
else if (data[i] != data[j]) {
b = input.substring(data[i], data[i] + word.length());
c = input.substring(data[j], data[j] + word.length());
}
}
}
if (a.equalsIgnoreCase(word)) {
count++;
}
System.out.println(count);
}
public static void main(String[] args) {
Calc();
}
}
using a while loop i finding the index of word given by the user in the sentence again given by the user.. I am storing those index in the array. for some reason that is not working.. so i found another way of implementing it. if the index of that word in the array is the equals each other then the word only exits once. I have got this to work.. but if the word exits more than once that is creating the problem..
Get the first letter of the word given by user.Next look at the sentence and find the letter.Then check the second letter of the word and compare it with the next letter in sentence . If its same again continue comparing .If not start again from next letter. Each time you get all the letters of the word and then a space you add 1 to a counter.Think that will work.
Take a look at String.indexOf(String, int). This finds the next position of the parameter String, starting at the parameter int.
Split can't be used? That seems rather odd. I'll bite though, and say simply that we don't have enough information to give a correct answer.
What is a word exactly?
How should symbols/letters be considered?
When is a sentence completed?
Should hyphened words be special?
Do we have 1 sentence and we are testing many words?
Do we have 1 word and many sentence?
What about substring matches (can vs canteen)?
Given what I can guess you should loop through the "sentence" tokenized the input by building "words" until you hit word boundary. Put the found words into a HashMap (keyed on the word) and increment the value for each word as you find it.
You need to call 'input.indexOf(word, fromIndex)' in a loop to find the string. Each time you call this function and it returns something other than -1 increment your count. When it returns -1 or you reach the end of the string stop. fromIndex will start at 0 and will need to be incremented each time you find a string by the length of the string.
Related
The input is supposed to be
ABDECDEABCAADD
ABCDE
The first line is a random piece of text. The second line is a circular shift.
The output is supposed to be:
yes
This program is supposed to take a piece of text and determine if it contains a circular shift based on the second line of input.
A circular shift is when you take the first letter of the string and move it to the back of the string. Thus creating a new string.
If the text entered contains a circular shift from the second line then the output would be yes otherwise it would be no.
Since ABDECDEABCAADD contains DEABC which is a shift of ABCDE the output would be yes.
Scanner scan = new Scanner(System.in);
String text;
System.out.println("Enter text:");
text=scan.nextLine();
System.out.println("Enter shift:");
String shift=scan.nextLine();
String[] split1=shift.split("");
String[] array2=new String[split1.length];
String[] array3=new String[split1.length];
for(int z=0;z<split1.length;z++) {
array2[split1.length-1]=split1[0];
for(int x=0;x<split1.length-1;x++) {
array2[x]=split1[x+1];
array3[0]=array2[x]+array2[x+1];
}
//if(text!=)
}
for(int y=0;y<array2.length;y++) {
System.out.print(array2[y]);
}
How I wanted to tackle this question was to first get the input then separate the second line into characters so I can create a circular shift. Once I'm done with that I would take the new order of characters and merge them to create a string.
I need help when it comes to the merging but also with how I can create multiple shifts.
If you see this pleas help.
Don't create shifts. For best performance, do it like this:
String text = "ABDECDEABCAADD";
String shift = "ABCDE";
Scan text for the first character in shift, i.e. scan for 'A'.
When found, match as many of the following characters as possible.
If not all characters in shift were matched, get the count of missing characters.
Grab that many characters from before the found 'A', if available.
If found and they match the remaining characters in shift, your search is done.
Repeat from step 1, searching for the next 'A'.
Example
static int matchShift(String text, String shift) {
if (shift.isEmpty())
throw new IllegalArgumentException("Shift value is empty");
char first = shift.charAt(0);
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == first) {
int j = 1;
while (j < shift.length() && i + j < text.length()
&& text.charAt(i + j) == shift.charAt(j))
j++;
if (j == shift.length())
return i; // Match found at index 'i', with unshifted value
int start = i + j - shift.length();
if (start >= 0 && text.substring(start, i).equals(shift.substring(j, shift.length())))
return start; // Match found at index 'start', with shifted value
}
}
return -1; // No match found
}
Test
public static void main(String[] args) {
test("ABDECDEABCAADD", "ABCDE");
}
static void test(String text, String shift) {
int i = matchShift(text, shift);
if (i == -1)
System.out.printf("'%s', '%s': No Match%n", text, shift);
else
System.out.printf("'%s', '%s': Match at index %d ('%s')%n",
text, shift, i, text.substring(i, i + shift.length()));
}
Output
'ABDECDEABCAADD', 'ABCDE': Match at index 5 ('DEABC')
It could also have responded with Match at index 4 ('CDEAB'). If that is important, change the logic to search for the last character instead of the first, match backwards, then compare substrings after.
I started this because I was totally bored but because of this error I have been sitting here since so long and finally decided to take this to stackOverFlow. Here is the code Which I wrote.
I was trying to print characters by skipping 1 index. But when there are duplicates I want to print a space which would differentitate words from big string.
Updated Question: Everything fixed except I cant increase I value more than 1. I commented it in below program. Please look at it.
Let me cut the chase and get to the point. I need this output " Vishnu Vardhan" from this String "aVeIwSjHaNgUaaVdAgRjDkHxAmN";
My only requirement is if the string has two same letters it has to print space. So "aVeIwSjHaNgU [aa] VdAgRjDkHxAmN" the aa in the brackets has to be replaced by space.
It has to be dynamic, if any char is repeated it has to print a space and jump to required next char and print it.
Here is the Updated program. Using help from one of the comments.
public class Decrypter {
public static void main(String[] args) {
String Text = "aVeIwSjHaNgUaaVdAgRjDkHxAmN";
char[] convertedText = Text.toCharArray();//converted string to char array
for (int i = 1; i < convertedText.length; i++) { //Looping it to print alternate chars
/* if the character at an index is same as the character at next index then
add a space and increase index value by 2 so I can print the required char*/
if (i + 1 < convertedText.length) {
if (Text.charAt(i) == Text.charAt(i + 1)) {
i++;// Increasing I value by 2 here will give me required output. Everything is perfect now
System.out.printf("%s ", convertedText[i]);
} else {
System.out.printf("%s", convertedText[i]);
i++;
}
}
}
}
}
Current output : VISHNUadgjkxm
Required output: VISHNU VARDHAN
i dont know if converting string to charArray is required but i hope this will do. comment below if you have questions open for revision.
String text = "aVeIwSjjHaNgUkkVarqddlhxn";
//this is the holder of your new processed text.
String newText = "";
//start of counter. it may start in any number depends on requirements.
int x = 0;
//loop while the x is lessthan the length of your string.
while(x < text.length()){
//check if the x + 1 is not equal to the length of your string to avoid StringIndexOutOfBoundsException
if((x+1) != text.length()){
//in this area it will check if the current char is the same on next index
if(text.charAt(x) == text.charAt(x+1)){
// this will concatenate/append the value of char with space
newText += text.charAt(x) +" ";
// this will increase the value of your x by 1 and at the bottom there are also x++ that will add 1 to your x so the total sum of x if (text.charAt(x) == text.charAt(x+1)) are true, will be 2.
x++;
}
}
newText += text.charAt(x);
x++;
}
System.out.println(newText);
output :
aVeIwSj jHaNgUk kVarqd dlhxn
if this is not what you looking for please kindly update your question.
Fixed:
/**
*
* #author Chintu
*/
public class Decrypter {
public static void main(String[] args) {
String Text = "aVeIwSjHaNgUkkVarqdlhxn";
char[] convertedText = Text.toCharArray();//converted string to char array
for (int i = 1; i < convertedText.length; i++) { //Looping it to print alternate chars
/* if the character at an index is same as the character at next index then
add a space and increase index value by 2 so I can print the required char*/
if (i+1 < convertedText.length) {
if (Text.charAt(i) == Text.charAt(i + 1)) {
i++;
System.out.printf("%s ",convertedText[i]);
}
}
System.out.printf("%s", convertedText[i]);
}
}
}
Fixed
public class Decrypter {
public static void main(String[] args) {
String Text = "aVeIwSjHaNgUaaVdAgRjDkHxAmN";
char[] convertedText = Text.toCharArray();//converted string to char array
for (int i = 0; i < convertedText.length; i++) { //Looping it to print alternate chars
/* if the character at an index is same as the character at next index then
add a space and increase index value by 2 so I can print the required char*/
if (i + 1 < convertedText.length) {
if (Text.charAt(i) == Text.charAt(i + 1)) {
i += 2;
System.out.printf(" %s", convertedText[i]);
} else {
i++;
System.out.printf("%s", convertedText[i]);
}
}
}
}
}
output: VISHNU VARDHAN
I know I'm missing some things and that's what I really need help with. The code doesn't work in all cases and am looking for help improving/fixing it.
Assignment:
The code I have so far:
public String word(int num, String words)
{
int l = words.indexOf(" ");
int r = words.indexOf(" ", l+1);
for(int i = 3; i <= num; i++){
l = r;
r = words.indexOf(" ", l+1);
//if(i != num)
// l = r;
}
String theword = words.substring(l,r);
return theword;
}
}
As this is clearly homework, I will give you text only.
Your approach may work eventually, but it is laborious and overly complicated, so it's hard to debug and hard to get right.
make use of String's API by using the split() method
after splitting the sentence into an array of word Strings, return the element at num less one (array are indexed starting at zero
check the length of the array first, in case there are less words than num, and take whatever action you think is appropriate in that case
For part 2, a solution in a simple form may be:
create a new blank string for the result
iterate over the characters of the given string adding the character to the front of the result string
make use of String's toUpperCase() method
Since this is homework and you have showed some effort. This is how you can do part 1 of your question. This code is pretty evident.
1) I am returning null if number is greater than the number of words in string as we dont want user to enter 5 when there are only 2 words in a string
2) Splitting the string by space and basically returning the array with the number mentioned by user
There are more conditions which you must figure out such as telling the user to enter a number of the string length since it would not give him any result and taking input from Scanner instead of directy adding input in method.
public static String word(int num, String words)
{
String wordsArr[] = words.split(" ");
if(num <= 0 || num > wordsArr.length) return null;
return (wordsArr[num-1]);
}
the second part of your question must be attempted by you.
Well... not often you see people coming here with homework AND showing effort at the same time so bravo :).
This is example of how you can split the string and return the [x] element from that string
public class SO {
public static void main(String[] args) throws Exception {
int number = 3;
String word = "Hello this is sample code";
SO words = new SO();
words.returnWord(number, word);
}
private void returnWord(int number, String word) throws Exception {
String[] words = word.split("\\s+");
int numberOfWords = words.length;
if(numberOfWords >= number) {
System.out.println(words[number-1]);
} else {
throw new Exception("Not enought words!!!");
}
}
}
Yes it is a working example but do not just copy and paste that for your homework - as simple question from teacher - What is this doing, or how this works and your out :)! So understand the code, and try to modify it in a way that you are familiar what is doing what. Also its worth getting some Java book - and i recommend Head first Java by O'Really <- v.good beginner book!
if you have any questions please do ask!. Note that this answer is not 100% with what the textbook is asking for, so you can modify this code accordingly.
As of part 2. Well what Bohemian said will also do, but there is a lot quicker solution to this.
Look at StringBuilder(); there is a method on it that will be of your interest.
To convert String so all letter are upper case you can use .toUpperCase() method on this reversed string :)
You can try:
public class trial {
public static void main(String[] args)
{
System.out.println(specificword(0, "yours faithfully kyobe"));
System.out.println(reverseString("derrick"));}
public static String specificword(int number, String word){
//split by space
String [] parts = word.split("\\ ");
if(number <= parts.length){
return parts[number];
}
else{
return "null String";
}
}
public static String reverseString(String n){
String c ="";
for(int i = n.length()-1; i>=0; i--){
char m = n.charAt(i);
c = c + m;
}
String m = c.toUpperCase();
return m;
}
}
For the first problem, I'll give you two approaches (1. is recommended):
Use the String.split method to split the words up into an array of words, where each element is a word. Instead of one string containing all of the words, such as "hello my name is Michael", it will create an array of the words, like so [hello, my, name, is, Michael] and that way you can use the array to access the words. Very easy:
public static String word(int num, String words)
{
// split words string into array by the spaces
String[] wordArray = words.split(" "); // or = words.split("\\s+");
// if the number is within the range
if (num > 0 && num <= wordArray.length) {
return wordArray[num - 1]; // return the word from the word array
} else { // the number is not within the range of words
return null;
}
}
Only use this if you cannot use arrays! Loop through the word until you have found enough spaces to match the word you want to find:
public static String word(int num, String words)
{
for (int i = 0; i < words.length(); i++) { // every character in words
if (words.substring(i, i+1).equals(" ")) { // if word is a space
num = num - 1; // you've found the next word, so subtract 1 (number of words left is remaining)
}
if (num == 1) { // found all words
// return this word
int lastIndex = i+1;
while (lastIndex < words.length()) { // until end of words string
if (words.substring(lastIndex, lastIndex+1).equals(" ")) {
break;
}
lastIndex = lastIndex + 1; // not a space so keep moving along the word
}
/*
// or you could use this to find the last index:
int lastIndex = words.indexOf(" ", i + 1); // next space after i+1
if (lastIndex == -1) { // couldn't find another space
lastIndex = words.length(); // so just make it the last letter in words
}*/
if (words.substring(i, i+1).equals(" ")) { // not the first word
return words.substring(i+1, lastIndex);
} else {
return words.substring(i, lastIndex);
}
}
}
return null; // didn't find word
}
As for the second problem, just iterate backwards through the string and add each letter to a new string. You add each letter from the original string to a new string, but just back to front. And you can use String.toUpperCase() to convert the string to upper case. Something like this:
public static String reverse(String str) {
String reversedString = ""; // this will be the reversed string
// for every character started at the END of the string
for (int i = str.length() - 1; i > -1; i--) {
// add it to the reverse string
reversedString += str.substring(i, i+1);
}
return reversedString.toUpperCase(); // return it in upper case
}
I have a large string like "wall hall to wall hall fall be", and I want to print longest strings. Then i want to know how many times all longest strings Is repeated?
For exampele,longest strings are:
wall Is repeated 2
hall Is repeated 2
fall Is repeated 1
This is my code:
public void bigesttstring(String str){
String[] wordsArray=str.split(" ");
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
}
}
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
But this code only prints "wall".
for count repeated String(i mean "maxWord"),this code write:
int count=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
count++;
}
}
and for display other longest strings i have this code:
int k=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
k++;
}
}
String[] other=new String[k];
int o=0;
for(int i=0;i<wordsArray.length;i++){
if(maxWord.equals(wordsArray[i])){
continue;
}
if(maxsize==wordsArray[i].length()){
other[o]=wordsArray[i];
o++;
}
}
I allowed to use this functions:
char char At(int i);
int ComoareTo(String another string);
boolean endsWith(String suffix);
int indexof();
int indexof(String str);
String substring();
char[] toCharArray();
String lowercase();
And want another code like this for shortest strings.
You have written
if(wordsArray[i].length()>maxsize)
For wall, hall and fall, it is only true for first wall. That's why you are getting wall and size 4.
Here you are not considering that the longest string length may be same for different string. You will have to store the longest string in an array and if condition should be
if(wordsArray[i].length()>=maxsize)
you will consider = and > case seperately. Since in the case of > you will have to delete all the string in array.
You need to change it to equal because currently if the words is the same length as the current largest word it will ignore it. Also if you want it to have the biggest words. You need to store them in an array. I implemented it here.
package OtherPeoplesCode;
public class string {
public static void main(String[] args) {
bigeststring("wall hall to wall hall fall be");
}
public static void bigeststring(String str){
String[] wordsArray=str.split(" ");
String[] biggestWordsArray = new String[wordsArray.length];
int x = 0;
int n= str.trim().split("\\s+").length;
int maxsize=0;
String maxWord="";
for(int i=0;i<wordsArray.length;i++){
if(wordsArray[i].length()>maxsize){
maxWord=wordsArray[i];
maxsize=wordsArray[i].length();
for(int y = 0; y <= biggestWordsArray.length -1; y++){
biggestWordsArray[y] = "";
}
}
else if(maxsize==wordsArray[i].length()){
biggestWordsArray[x] = wordsArray[i];
x++;
}
}
if(biggestWordsArray[0].equals("")){
System.out.println("Max sized word is "+maxWord+" with size "+maxsize);
}
else if(!(biggestWordsArray[0].equals(""))){
System.out.println("TIE!");
for(int y = 0; y <= biggestWordsArray.length -1; y++){
if(!(biggestWordsArray[y].equals(""))){
System.out.print("Word #" + y + " is ");
System.out.println(biggestWordsArray[y]);
}
}
}
}
}
EDIT: This is the working code, sorry about the delay.
Using Map is possibly the most straight-forward and easy way to do. However if you said your teacher don't allow you to use that, may you tell us what is allowed? So that we don't end up wasting time suggesting different methods and end up none of them is acceptable because your teacher doesn't allow.
One most brute force way that I can suggest you to try is (lots of place for optimization, but I think you may want the easiest way):
loop through the list of words, and find out the length of the longest word and number of words with such length
Create a new array with "number of word" you found in 1. Loop through the original word list again, for each word with length == maxWordLength, put that in the new array IF it is not already existed in it (a simple check by a loop.
Now you have a list that contains all DISTINCT words that are "longest", with some possible null at the end. In order to display them in a format like "word : numOfOccurence", you can do something like
loop through result array until you hit null. For each word in the result array, have a loop in the original word list to count its occurence. Then you can print out the message as you want
in psuedo code:
String[] wordList = ....;
int maxLen = 0;
int maxLenOccurence = 0;
foreach word in wordList {
if word is longer then maxLen {
maxLen = word's length
maxLenOccurence = 1;
}
else if word's length is equals to maxLen {
maxLenOccurence ++
}
}
// 2,3
String[] maxLenWordList = new String[maxLenOccurence];
foreach word in wordList {
else if word's length is equals to maxLen {
for i = 0 to maxLenWordList length {
if (maxLenWordList[i] == word)
break
if (maxLenWordList[i] == null
maxLenWordList[i] = word
}
}
//4
foreach maxLenWord in maxLenWordList {
count = 0
foreach word in wordList {
if maxLenWord == word
count ++
}
display "Max sized word is "+ maxLenWord + " with size " + count
}
Another way doesn't involve other data structure is:
Have the word list
Sort the word list first by length then by the literal value
First element of the result list is the longest one, and string with same value become adjacent. You can do a loop print out all matching and its count (do some thinking by yourself here. Shouldn't be that hard)
Also you can use this;
String[] allLongestStrings(String[] inputArray) {
List<String> list = new ArrayList<String>();
int max = 0;
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n > max) {
max = n;
}
}
for (int i = 0; i < inputArray.length; i++) {
StringBuilder s = new StringBuilder(inputArray[i]);
int n = s.length();
if (n == max) {
list.add(s.toString());
}
}
return list.toArray(new String[list.size()]);
}
I froze onto the following code for counting occurence of a character in a string:
public static void main(String[] args) {
String source = "hello low how ale you";
Scanner in = new Scanner(System.in);
String temp = in.nextLine();
char test = temp.toCharArray()[0];
int fromIndex = 0;
int occurences =0;
while(fromIndex>-1)
{
fromIndex = source.indexOf(test, fromIndex);
System.out.println("found at"+fromIndex);
//if(fromIndex!=-1) occurences++;
}
System.out.println(occurences);
}
The loop runs infinitely if the "if(fromIndex!=-1)" line is commented out!
The loop properly terminates if the same line is uncommented.
Its strange to observe that loop's termination depends on variable fromIndex and not on the updation of variable occurences which is being updated inside the If block.
Any guesses as to why this is happening?
the fromIndex value is not changing in the subsequent iterations. Thats the reason behind the endless loop.Thats because fromIndex will give the exact index of the character. increment the fromIndex by 1 for the next loop and tht would solve the problem.
while(fromIndex>-1)
{
fromIndex = source.indexOf(test, fromIndex+1);
System.out.println("found at"+fromIndex);
if(fromIndex!=-1) occurences++;
}
}
Hope this helps.
If you are not strict on using an approach like in your code, I suggest you to use a regex. You will have cleaner and less code, too. Try the code snippet below, let's say you have character ch:
char ch = 'o';
String input = "Hi there boys! Come on!";
String regex = ch + "";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
ArrayList<String> matches = new ArrayList<String>();
while (m.find())
matches.add(m.group());
System.out.println(matches.size());
I think you are trying to do something like below.
public class Solution {
public static void main(String[] args) {
String source = "hello low how ale you";
char test = 'u';
int fromIndex = 0;
int occurrences = 0;
int length = source.length();
while (fromIndex < length) {
int index = source.indexOf(test, fromIndex);
if (index != -1) {
occurrences++;
fromIndex = index;
}
fromIndex++;
}
System.out.println(occurrences);
}
}
Some explanation-
Suppose you need to find 'h' in the given string, you will start from 0, so your fromIndex initialization will be 0.
You search from initial position till the end of the string. That's why in the while loop, you need to give your condition as, fromIndex < length.
Now, try to find the occurrence of your test. If there is a test character, you get its character. Else you get -1. Store it in index.
Now if the index is not -1, assign it to fromIndex. Because you will now search starting from this position. Not again from 0.
Increment fromIndex. This will be done regardless of the value of index variable.
Now analyze your code for errors.