Find word in User Content without using .split() or StringTokenizer - java

I'm working on a program that ask the user to input a phrase and an integer. The integer is used to identify which word will be return from the phrase. For example, if they enter 5, the program should return to the user the fifth word in the sentence.
System.out.println("Your word is: " +combineString(phrase,numWord));
This is my work so far, there is a main to output,
public static String combineString(String newPhrase, int newNum) {
int countWords = 0;
String word = "";
//words count. I'll +1 everytime using countWord the match the amount of words
for(int i=0; i< newPhrase.length(); i++) {
if(newPhrase.charAt(i) == ' ') {
countWords++;
}
}
//return the last word. Ex: 15 words in a phrase if user pick the 18th word it will return the 15th word.
if(countWords+1 < newNum || countWords+1 <= newNum) {
word += newPhrase.substring(newPhrase.lastIndexOf(' ')+1, newPhrase.length()-1);
}
else if(newNum <=0) { //return null if the user pick 0 or less than 0
word += null;
}
return word;
And I was thinking a lot on how to work on the middle part and my thought are if the user pick numWord = 5, then in order to return the fifth word in that sentence, I'm gonna need to use "newPhrase.substring(space 4th +1, space 5th)". And this is where I stuck because I don't know how to start, and how to get to space 4th.

public static String combineString(String newPhrase, int newNum) {
if(newNum<=0)
return null;
String word = "";
String [] match = new String[newNum];
int j =0;
for(int i=0; i< newPhrase.length(); i++) {
word = word + newPhrase.charAt(i);
if(newPhrase.charAt(i) == ' ') {
match[j] = word;
if(j+1 == newNum) {
return word; // returns the specified word
}
j++;
word = "";
}
}
return word; //returns last word
}
This code should work for you. If that's the case accept the answer.

If you want to go really low level, then you can go lower than subString and operate on single characters. This way its easy to skip other characters than blank. Its also a step towards the way regular expression get executed by transforming them to finite state automatons.
enum ScanState {WHITESPACE, WORD}
private final static Set<Character> whitespace = new HashSet<>(Arrays.asList('"', ',', '.', '?', '!', '-', ';', ' '));
#Test
public void testTokenize() {
char[] text = "No, it's been \"yes?\", and not \"no!\" - hasn't it?".toCharArray();
List<String> expected = Arrays.asList("No", "it's", "been", "yes", "and", "not", "no", "hasn't", "it");
assertEquals(expected, tokenize(text));
}
private List<String> tokenize(char[] text) {
List<String> result = new ArrayList<String>();
char[] word = new char[256];
int maxLetter = 0;
ScanState prevState = ScanState.WHITESPACE;
for (char currentChar : text) {
ScanState currState = whitespace.contains(currentChar) ? ScanState.WHITESPACE : ScanState.WORD;
if (prevState == ScanState.WORD && currState == ScanState.WORD) {
word[maxLetter++] = currentChar;
}
if (prevState == ScanState.WORD && currState == ScanState.WHITESPACE) {
word[maxLetter++] = currentChar;
result.add(String.valueOf(word, 0, maxLetter - 1));
}
if (prevState == ScanState.WHITESPACE && currState == ScanState.WORD) {
maxLetter = 0;
word[maxLetter++] = currentChar;
}
prevState = currState;
}
return result;
}

Related

Turning the Nth (input from user) number into Uppercase and the rest will be in Lowercase

I will ask this again. I have this problem which is to create a program that would read a string input from the user (sentence or word). And the Nth number (from the user) will turn into upper case and the rest will be in lowercase.
Example:
string = "good morning everyone"
n = 2
Output = gOod mOrning eVeryone
for (int x = 0; x < s.length(); x++)
if (x == n-1){
temp+=(""+s.charAt(x)).toUpperCase();
}else{
temp+=(""+s.charAt(x)).toLowerCase();
}
s=temp;
System.out.println(s);
}
Output: gOod morning everyone
I know what you want to happen - but you didn't phrase your question very well. The only part your missing is iterating through every word in the sentence. If you asked "how do I apply a function on every word in a String" you likely would have gotten a better response.
This is a bit sloppy since it adds a trailing " " to the end - but you could fix that easily.
public class Test {
static String test = "This is a test.";
public static void main(String[] args) {
String[] words = test.split(" ");
String result = "";
for (String word : words) {
result += nthToUpperCase(word, 2);
result += " ";
}
System.out.println(result);
}
public static String NthToUpperCase(String s, int n) {
String temp = "";
for (int i = 0; i < s.length(); i++) {
if (i == (n-1)) {
temp+=Character.toString(s.charAt(i)).toUpperCase();
} else {
temp+=Character.toString(s.charAt(i));
}
}
return temp;
}
}
You can do this with two for loops. Iterate over each word and within the iteration iterate over each character.
toUpperCase(2, "good morning everyone");
private static void toUpperCase(int nth, String sentence) {
StringBuilder result = new StringBuilder();
for(String word : sentence.split(" ")) {
for(int i = 0; i < word.length(); i++) {
if(i > 0 && i % nth - 1 == 0) {
result.append(Character.toString(word.charAt(i)).toUpperCase());
} else {
result.append(word.charAt(i));
}
}
result.append(" ");
}
System.out.println(result);
}
gOoD mOrNiNg eVeRyOnE

Java Programming: Replace all but first and last letters of each word with "_"

The purpose of this method is replace all but the first and last letters of each word with "_". I'm a complete novice when it comes to coding, so I'm certain my code is fairly incorrect. I think where my code starts functioning improperly is with the while loop.
EDIT: How do I make this method without using arrays or extra methods, like the split method?
public static String blankWords(String s1) {
StringBuilder sb = new StringBuilder();
if(s1.length() > 2) {
sb.append(s1.charAt(0));
for(int x = 1; x < s1.length() - 1; x = x + 1) {
char y = ' ';
while(y != s1.charAt(x)) {
sb.append("_");
x = x + 1;
}
}
sb.append(s1.charAt(s1.length() - 1));
return sb.toString();
}
return s1;
}
What my code is outputting:
HW2.blankWords("This is a Test.")
java.lang.StringIndexOutOfBoundsException: String index out of range: 15
at java.lang.String.charAt(Unknown Source)
at HW2.blankWords(HW2.java:73)
What my code should output:
HW2.blankWords("This is a Test.")
"T__s is a T__t."
Here is a pretty simple solution:
class Scratch {
public static void main(String[] args) {
System.out.println(blankWords("My name is sam orozco"));
}
public static String delim = "_";
public static String blankWords(String s1) {
// this split arg on one or more space
String[] words = s1.split("\\s+");
StringBuilder response = new StringBuilder();
for (String val : words) {
val = convertWord(val);
response.append(val).append(" ");
}
return response.toString().trim();
}
public static String convertWord(String val) {
int len = val.length();
StringBuilder bldr = new StringBuilder();
int index = 0;
for (char ch : val.toCharArray()) {
if (index == 0 || index == len - 1) {
bldr.append(ch);
} else {
bldr.append(delim);
}
index++;
}
return bldr.toString();
}
}
You can do this using a StringTokenizer that will extract words based on a list of delimiters. Since you want to keep those delimiters in the output, you'll instruct the tokenizer to return them as tokens:
String blankWords(String s) {
// build a tokenizer for your string, listing all special chars as delimiters. The last argument says that delimiters are going to be returned as tokens themselves (so we can include them in the output string)
StringTokenizer tokenizer = new StringTokenizer(s, " .,;:?!()[]{}", true);
// a helper class to build the output string; think of it as just a more efficient concat utility
StringBuilder sb = new StringBuilder();
while (tokenizer.hasMoreTokens()) {
String blankWord = blank(tokenizer.nextToken());
sb.append(blankWord);
}
return sb.toString();
}
/**
* Replaces all but the first and last characters in a string with '_'
*/
private String blank(String word) {
// strings of up to two chars will be returned as such
// delimiters will always fall into this category, as they are always single characters
if (word.length() <= 2) {
return word;
}
// no need to iterate through all chars, we'll just get the array
final char[] chars = word.toCharArray();
// fill the array of chars with '_', starting with position 1 (the second char) up to the last char (exclusive, i.e. last-but-one)
Arrays.fill(chars, 1, chars.length - 1, '_');
// build the resulting word based on the modified array of chars
return new String(chars);
}
Here is the contents of a test that validates this implementation, using TestNG:
#Test(dataProvider = "texts")
public void testBlankWords(String input, String expectedOutput) {
assertEquals(blankWords(input), expectedOutput);
}
#DataProvider
public Object[][] texts() {
return new Object[][] {
{"This is a test.", "T__s is a t__t."},
{"This one, again, is (yet another) test!", "T__s o_e, a___n, is (y_t a_____r) t__t!"}
};
}
The main drawback of this implementation is that StringTokenizer requires you to list all the delimiters by hand. With a more advanced implementation, you can consider a delimiter any character that returns false for Character.isAlphabetic(c) or however you decide to define your non-word chars.
P.S.
This could be a "more advanced implementation", as I mentioned above:
static String blankWords(String text) {
final char[] textChars = text.toCharArray();
int wordStart = -1; // keep track of the current word start position, -1 means no current word
for (int i = 0; i < textChars.length; i++) {
if (!Character.isAlphabetic(textChars[i])) {
if (wordStart >= 0) {
for (int j = wordStart + 1; j < i - 1; j++) {
textChars[j] = '_';
}
}
wordStart = -1; // reset the current word to none
} else if (wordStart == -1) {
wordStart = i; // alphabetic characters start a new word, when there's none started already
} else if (i == textChars.length - 1) { // if the last character is aplhabetic
for (int j = wordStart + 1; j < i; j++) {
textChars[j] = '_';
}
}
}
return new String(textChars);
}
No while loop necessary!
Look ahead by 1 character to see if it's a space, or if the current character is a space, in that case you append it. Otherwise you make sure to add the next character (skipNext false).
Always add the last character
public static String blankWords(String s1) {
StringBuilder sb = new StringBuilder();
if(s1.length() > 2) {
Boolean skipNext = false;
for(int x = 0; x < s1.length() - 1; x = x + 1) {
if(s1.charAt(x) == ' ' || s1.charAt(x + 1) == ' ') {
sb.append(s1.charAt(x));
skipNext = false;
}
else {
if(skipNext) {
sb.append('_');
}
else {
sb.append(s1.charAt(x));
skipNext = true;
}
}
}
sb.append(s1.charAt(s1.length() - 1));
return sb.toString();
}
return s1;
}
For the more advanced programmer, use regular expression.
public static String blankWords(String s1) {
return s1.replaceAll("\\B\\w\\B", "_");
}
This correctly keeps the final t, i.e. blankWords("This is a Test.") returns "T__s is a T__t.".

Trouble converting normal sentences to pig latin

I'm trying to convert a sentence to pig latin but can't seem to get the correct output to work. For example the input
the rain in spain stays mainly in the plain yields an output of ethay ethay ethay with my current code whereas the expected output is ethay ainray inay ainspay aysstay ainlymay inay ethay ainplay
For those unfamiliar, the basic rules of pig latin are:
If the word begins with a consonant, take the beginning consonants up until the first vowel and move them to the end of the word. Then append ay at the very end. (so cricket would become icketcray)
If the word begins with a vowel, simply add ay to the end. (apple would become appleay)
If y is the first letter in the word, treat it as a consonant, otherwise it is used as a vowel. (young would become oungyay and system would become ystemsay)
My code is as follows:
import java.util.Scanner;
public class PigLatin{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.next();
String piglatin = translateSentence(line);
System.out.println(piglatin);
}
public static String translateSentence(String line){
for (int i =0; i < line.length(); i++ ) {
char c = line.charAt(i);
//for loop to analyze each word
if (Character.isAlphabetic(c)) {
//if (i <='a' || i<='A' || i>='z' || i>='Z'){
String piglatin = translateword(line);
return piglatin;
}
}
return line;
}
public static String translateword(String line) {
Scanner scan = new Scanner(System.in);
int position = firstVowel(line);
String words = "";
String output = "";
for(int i = 0; i<line.length();i++){
words = "";
if (firstVowel(line) == 0) {
words = line + "-way";
} else if (firstVowel(line) == -1) {
words = line + "";
} else {
String first = line.substring(position);
String second = line.substring(0,position) + "ay";
words = first + second;
}
output = output + " " + words;
//words = "";
}
return output;
}
public static int firstVowel(String line) {
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == 'a' || line.charAt(i) == 'e'
|| line.charAt(i) == 'i' || line.charAt(i) == 'o'
|| line.charAt(i) == 'u') {
return i;
}
}
return -1;
}
}
Any help is greatly appreciated, thank you.
first write a separate function to get list of words from line
public String[] getWords(String line) {
String list[]=new String[100];
int j=0;
int end;
end=line.indexOf(' ');
while (end!=-1) {
list[j]=line.substring(0, end);
line=line.substring(end+1,line.length());
j++;
end=line.indexOf(' ');
}
list[j]=line.substring(0,line.length());
return list;
}
then modify your translate line to call translate word multiple times, each time pass a single word.
Assuming your translateWord() returns a single correctly translated word. translateLine change in the following way:
if (Character.isAlphabetic(c)) {
String wordList[]=getWords(line);
String piglatin="";
int i=0;
while(!line[i].equals("")) {
piglatin = piglatin+translateword(word[i]);
i++;
}
return piglatin;
}

recursive function that checks if there are k words that they "charecter equale" to a given word

we will say that two words are "charecter equale" if both of them has the same charecter, for example: baac and abac are charecter equale, I am trying to write a recursive function that gets a string s, a word w and integer k, that checks if there are exactliy k words in the string that they charecter equale to the word, for example: the function should return true for the word abac , the string aabc abdca caba xyz ab and the number k=2.
Ineed help at the recursive part, i.e the function searchMixed, my idea was first the check if the string contain only on word (base case),
the general case is to call the function searchMixed without the first word
public class recursion1 {
public static void main(String[] args) {
boolean result=searchMixed("abac","aabc abdca caba xyz ab",2);
System.out.println("result: "+result);
}
public static boolean searchMixed(String word, String s, int k)
{
if(s.indexOf(' ')==-1 && isEquale(word,s) && k==1)
return true;
if(s.indexOf(' ')==-1 && !isEquale(word,s) && k==1)
return false;
int pos=s.indexOf(' ');
System.out.println("index of"+ s.indexOf(' '));
String first_word=first_word=s.substring(0,pos);
if(isEquale(word, first_word))
searchMixed(word, s.substring(pos+1), k-1);
else
searchMixed(word, s.substring(pos+1), k);
return false;
}
.
//this function works fine, the function checks if two words are charecter equale
public static boolean isEquale(String word, String sub_string)
{
if(word.length()!=sub_string.length())
return false;
char[] s33=new char[sub_string.length()];
char[] sww=new char[word.length()];
for(int i=0;i<sub_string.length();i++)
s33[i]=sub_string.charAt(i);
for(int i=0;i<word.length();i++)
sww[i]=word.charAt(i);
for(int i=0;i<word.length();i++)
{
for(int j=0;j<sub_string.length();j++)
{
if(sww[i]==s33[j])
s33[j]='#';
}
}
for(int i=0;i<sub_string.length();i++)
if(s33[i]!='#')
return false;
return true;
}
}
YourString = YourString.replaceAll("\\s+", " ");
String[] words = YourString.split(" ");
... to split the words.
static int n = 0;
static String keyword = "aabc";
static String[] words = null;
public static void main()
{
n = 0;
// Let's assume you accept 'k' here.
String YourString = "aabc baca hjfg gabac";
words = YourString.split(" ");
rec(words[0]);
if (k <= n)
System.out.println(true);
else
System.out.println(false);
}
static int pos = 0;
public static void rec(String word)
{
boolean flag = true;
word += " ";
if(word.length() != keyword.length() + 1)
{
flag = false;
}
for(int i = 0; i < keyword.length() && flag; i++)
{
for(int j = 0; j < word.length(); j++)
{
if(word.charAt(j) == keyword.charAt(i))
{
word = word.substring(0, j) + word.substring(j+1);
break;
}
}
if(word.equals(" "))
{
n++;
break;
}
}
if(pos + 1 != words.length)
{
rec(words[++pos]);
}
}
Now, let me explain:
In the recursive method rec(String word), a space is added to it at the end of the word being checked (so that substring(j+1) does not go out of bounds)
If the keyword and the checked word are of different lengths, it stops checking, and moves on to '5'.
If the two words are of same lengths, the loop removes a single similar character from the word (That's what word = word.substring(0, j) + word.substring(j+1); does).
At the end of the loop, if all that is remaining of the word is a space, then the counter n increases by 1 and the loop exits.
If there is more than or equal to one more Strings in the array, position of the word being checked in the array increases by 1, and the next word in the array is passed to the rec(String word) method.

Reverse every 2nd word of a sentence

I am trying to reverse every 2nd words of every single sentence like
If a given string is :
My name is xyz
The desired output should be :
My eman is zyx
My current output is:
Ym eman s1 zyx
I am not able to achieve my desired output.Don't know what I am doing wrong here
Here is my code
char[] sentence = " Hi my name is person!".toCharArray();
System.out.println(ReverseSentence(sentence));
}
private static char[] ReverseSentence(char[] sentence)
{
//Given: "Hi my name is person!"
//produce: "iH ym eman si !nosrep"
if(sentence == null) return null;
if(sentence.length == 1) return sentence;
int startPosition=0;
int counter = 0;
int sentenceLength = sentence.length-1;
//Solution handles any amount of spaces before, between words etc...
while(counter <= sentenceLength)
{
if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word
{
//swap from startPos to counter - 1
//set start position to -1 and increment counter
int begin = startPosition;
int end;
if(sentenceLength == counter)
{
end = counter;
}
else
end = counter -1;
char tmp;
//Reverse characters
while(end >= begin){
tmp = sentence[begin];
sentence[begin] = sentence[end];
sentence[end] = tmp;
end--; begin++;
}
startPosition = -1; //flag used to indicate we have no encountered a character of a string
}
else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position
{
startPosition = counter;
}
counter++;
}
return sentence;
}
If you want to reverse the alternate word you can try something like splitting the whole String into words delimited by whitespaces and apply StringBuilder reverse() on every second word like :-
String s = "My name is xyz";
String[] wordsArr = s.split(" "); // broke string into array delimited by " " whitespace
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i< wordsArr.length; i++){ // loop over array length
if(i%2 == 0) // if 1st word, 3rd word, 5th word..and so on words
sb.append(wordsArr[i]); // add the word as it is
else sb.append(new StringBuilder(wordsArr[i]).reverse()); // else use StringBuilder revrese() to reverse it
sb.append(" ");// add a whitespace in between words
}
System.out.println(sb.toString().trim()); //remove extra whitespace from the end and convert StringBuilder to String
Output :- My eman is zyx
You can solve your problem vary easy way! Just use a flag variable which will indicate the even or odd position, more precisely whether any word will gonna be reversed or not!
Look at the following modification I made in your code, just added three extra line:
private static boolean flag = true;// added a variable flag to check if we reverse the word or not.
private static char[] ReverseSentence(char[] sentence)
{
//Given: "Hi my name is person!"
//produce: "iH ym eman si !nosrep"
if(sentence == null) return null;
if(sentence.length == 1) return sentence;
int startPosition=0;
int counter = 0;
int sentenceLength = sentence.length-1;
//Solution handles any amount of spaces before, between words etc...
while(counter <= sentenceLength)
{
if(sentence[counter] == ' ' && startPosition != -1 || sentenceLength == counter) //Have passed over a word so upon encountering a space or end of string reverse word
{
flag = !flag; // first time (odd position) we are not going to reverse!
//swap from startPos to counter - 1
//set start position to -1 and increment counter
int begin = startPosition;
int end;
if(sentenceLength == counter)
{
end = counter;
}
else
end = counter -1;
char tmp;
//Reverse characters
while(end >= begin & flag){ //lets see whether we are going to reverse or not
tmp = sentence[begin];
sentence[begin] = sentence[end];
sentence[end] = tmp;
end--; begin++;
}
startPosition = -1; //flag used to indicate we have no encountered a character of a string
}
else if(sentence[counter] !=' ' && startPosition == -1) //first time you encounter a letter in a word set the start position
{
startPosition = counter;
}
counter++;
}
return sentence;
}
Input
My name is xyz
Output:
My eman is zyx
The following code does this "special reverse" which reverses any other word in the sentence:
public static void main(String[] args) {
String sentence = "My name is xyz";
System.out.println(specialReverse(sentence)); // My eman is zyx
}
private static String specialReverse(String sentence) {
String result = "";
String[] words = sentence.split(" ");
// we'll reverse only every second word according to even/odd index
for (int i = 0; i < words.length; i++) {
if (i % 2 == 1) {
result += " " + reverse(words[i]);
} else {
result += " " + words[i];
}
}
return result;
}
// easiest way to reverse a string in Java in a "one-liner"
private static String reverse(String word) {
return new StringBuilder(word).reverse().toString();
}
Just for completeness here's Java-8 solution:
public static String reverseSentence(String input) {
String[] words = input.split(" ");
return IntStream.range(0, words.length)
.mapToObj( i -> i % 2 == 0 ? words[i] :
new StringBuilder(words[i]).reverse().toString())
.collect(Collectors.joining(" "));
}
reverseSentence("My name is xyz"); // -> My eman is zyx
package com.eg.str;
// Without using StringBuilder
// INPUT: "Java is very cool prog lang"
// OUTPUT: Java si very looc prog gnal
public class StrRev {
public void reverse(String str) {
String[] tokens = str.split(" ");
String result = "";
String k = "";
for(int i=0; i<tokens.length; i++) {
if(i%2 == 0)
System.out.print(" " + tokens[i] + " ");
else
result = tokens[i];
for (int j = result.length()-1; j >= 0; j--) {
k = "" + result.charAt(j);
System.out.print(k);
}
result = "";
}
}
public static void main(String[] args) {
StrRev obj = new StrRev();
obj.reverse("Java is very cool prog lang");
}
}
//reverse second word of sentence in java
public class ReverseSecondWord {
public static void main(String[] args) {
String s="hello how are you?";
String str[]=s.split(" ");
String rev="";
for(int i=0;i<str[1].length();i++)
{
char ch=str[1].charAt(i);
rev=ch+rev;
}
str[1]=rev;
for(int i=0;i<str.length;i++)
{
System.out.print(str[i]+" ");
}
}
}

Categories