Regular expression to match an specific word in Java - java

I am trying to make a program that should checks if the string that the program is currently looking at, contains the word ing in that specific order. I figured out to just split the string with spaces, so each word can be looked at individually. I am stuck on the if condition. The if condition determines if the word has ing in it. For the assignment I can only use one loop and two if statements. I cannot use the string methods tolower or upppercase. Also this what the output needs to look like: (for the output i have a test class that gives me strings to test out)
Words with ing:
Singing Dancing
if I do not find any words what have ing the output should like this
There are no words with ing
Here is my code till now:
public class EndsWith
{
public static void endsWithIng (String s)
{
String[] a = s.splits(" ");
for(int i = 0; i < a.length; i++)
{
// if()
System.out.print(a[i] + "");
}
}
}

I found the answer for my problem. I forgot to mention that the problem also required a specific print statement. My solution is similar but I made a new string and added any words that I found with ing to that new string. Also I used a counter to keep track if a word with ing is even found in the first place. If it is not than I printed after the loop no words with ing found.
public class EndsWith
{// start of cLASS
public static void endsWithIng (String s)
{// START of method
String ing="";
String compare="";
String [] a = s.split(" ");
//System.out.println("Words with ing: ");
int i;
int count=0;
for(i=0;i<a.length;i++)
{//start of for
compare=a[i];
if(compare.matches(".*[iI][nN][gG].*"))
{ //start of if
//System.out.print(compare + " ");
count++;
ing+=a[i] +" ";
}
}
if(count==0)
{
System.out.println("There are no words with ing");
}
else
{
System.out.println("Words with ing: ");
System.out.println(ing);
}
}
}

I think you are looking to split on one (or more) white-space characters. You can also use String.endsWith(String)1. Something like,
public static void endsWithIng(String s) {
String[] a = s.split("\\s+");
for (int i = 0; i < a.length; i++) {
if (a[i].toLowerCase().endsWith("ing")) {
System.out.print(a[i] + " ");
}
}
}
or you could use an enhanced for-each loop like2
public static void endsWithIng(String s) {
String[] a = s.split("\\s+");
for (String value : a) { // <-- for each value in array a
// This checks if the last three characters make the String "ing"
if ("ing".equalsIgnoreCase(value.substring(value.length() - 3))) {
System.out.print(value + " ");
}
}
}
To use a regular expression, beyond String.split(String), you can use String.matches(String) like
public static void endsWithIng(String s) {
String[] a = s.split("\\s+");
for (String value : a) { // <-- for each value in array a
// This test ignores case for iI nN gG
if (value.matches(".*[(i|I)(n|N)(g|G)]$")) {
System.out.println(value);
}
}
}
1You since added the stipulation that you cannot use toLowerCase. Next time, for better help faster, please give all the requirements when you ask the question.
2This example uses Yoda conditions.

Related

Java Reverse a sentence but not punctuation

Input: My name is Bob.
Output: Bob is name My.
I have seen plenty of examples on how to reverse each word and then word sequence in a sentence. However, I do not think I have seen one that I want-example above. This forum was not helpful, because it only focuses on double quote on start and end of a sentence: How to reverse words in a string but keep punctuation in the right place?
What I tried
public void rev2(String str) {
String[] arrStr = str.split(" ");
for (int i = arrStr.length - 1; i >= 0; i--) {
if (!arrStr[i].contains(".")) {
System.out.print(arrStr[i] + " ");
}
}
}
public static void main(String[] args) {
Test t = new Test();
t.rev2("My name is Bob.");
}
The code above does not work as expected. I probably can convert each string to char and use Character.isAlphabet() or may be use pattern?
I could use some ideas. Thanks in advance for your time and help.
Here is a solution that works within the constraints of the question (some of which are assumed):
public void rev2(String str) {
String[] arrStr = str.split(" ");
for (int i = arrStr.length - 1; i >= 0; i--) {
boolean punct = i <= 0 || arrStr[i - 1].contains(".");
if (!arrStr[i].contains(".")) {
System.out.print(arrStr[i]);
} else {
System.out.print(arrStr[i].substring(0, arrStr[i].length() - 1));
}
System.out.print((punct ? ". " : " "));
}
}
public static void main(String[] args) {
Tester t = new Tester();
t.rev2("My name is Bob. I am happy.");
}
Explanation:
The boolean punct looks ahead to see if the next element contains a ".". If so, we are on a sentence boundry and so added a . after the current word. If not, we just put a space. We also add a "." if we are on the last element in the array.
Output:
happy am I. Bob is name My.
If all you want to do regarding punctuation is keep the period at the end of the sentence, you can print the words followed by a space or by the period depending on whether they are the first word or not, and you can remove the period from the last word by calling substring(). Something like this:
public class Test {
public void rev2(String str) {
String[] arrStr = str.split(" ");
for (int i = arrStr.length - 1; i >= 0; i--) {
if (!arrStr[i].contains(".")) {
System.out.print(arrStr[i] + (i == 0 ? "." : " "));
} else {
System.out.print(arrStr[i].substring(0, arrStr[i].length() - 1) + " ");
}
}
}
public static void main(String[] args) {
Test t = new Test();
t.rev2("My name is Bob.");
}
}
Output: Bob is name My.
If you want a less verbose code:
var list = Arrays.asList("My name is Bob".split(" "));
Collections.reverse(list);
list.stream().map(str -> str.concat(" ")).forEach(System.out::print);

A method that return single words from a String

As I mentioned in the title, i want to create a method in java that find each word from a String and print it out.
That is how it (more less) look like:
public int findFirstLetter(int pos, String text)
{
while (pos<text.length())
{
if (Character.isLetter(text.charAt(pos))==true&&(pos == 0||Character.isLetter(text.charAt(pos-1))==false)){return pos;}
pos++;
}
return -1;
}
public int findLastLetter(int pos, String text)
{
while (pos<text.length()){
if (Character.isLetter(text.charAt(pos))==true&&(pos+2>text.length()||Character.isLetter(text.charAt(pos+1))==false)){return pos;}
pos++;
if (pos == -1){break;};
}
return -1;
}
public void testString (String text)
{
int first = findFirstLetter(0,text);
int last = findLastLetter(0,text);
String word = "";
int startWord = 0;
int i = 0;
while (first!=-1)
{
word = text.substring(first, last+1);
System.out.println("word: "+word);
startWord = text.indexOf(word)+1;
first = findFirstLetter(startWord,text);
if(first == -1){break;}
last = findLastLetter(first,text);
}
When i provide some String as input to this method, the loop is starting to repeat from the middle and doesn't reach the end. For example, in the last phrases the method is repeating "the loop is" over and over again. Could someone give me some advice in order to find what is wrong?
As #Tim Biegeleisen stated in it's comment, you could use split in order to get the words, put them into an array and loop over it in order to print them. Please note that two Options are provided and you should choose 1 of them. If you're learning Java, the second option is more readable and comprehensible.
public void printWords(String s) {
String [] words = s.split("\\s+"); //Option 1: Tim Biegelsman regex
String [] words = s.split(" "); //Option 2: if the words are separated by blanks
for(String word : words) {
System.out.println(word);
}
}
Note also that you could save a line of code in this way:
public void printWords(String s) {
for(String word : s.split(" ")) {
System.out.println(word);
}
}

Return word specified by the integer

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
}

Text Processing Assignment

I am trying to write a few methods for my homework assignment but I don't know what to do.
I've tried a bunch of things but none seemed to work.
First Question is how do i take a string I have and return it with no spaces. trim() only eliminates the first and last whitespace of the sentence(getNoSpaceString method).
Also I am trying to count the number of digit words my sentence has aka one is 1 digit word.
My code is below(digitWordCount method).
import java.util.*;
public class StringProcessor {
private String noSpaces;
private String input, noVowels;
private String noDigitWords;
private int numOfWords = 0, uppercaseLetters = 0,
numOfDigits = 0, digitWords = 0;
public StringProcessor()
{
input = "";
}
public StringProcessor(String s)
{
StringTokenizer str = new StringTokenizer(s);
numOfWords = str.countTokens();
for (int i = 0; i < s.length(); i++)
{
if (Character.isUpperCase(s.charAt(i)))
uppercaseLetters++;
}
for (int i = 0; i < s.length(); i++)
{
if (Character.isDigit(s.charAt(i)))
numOfDigits++;
}
if (str.nextToken().equalsIgnoreCase("one"))
digitWords++;
}
public void setString(String s)
{
input = s;
}
public String getString()
{
return input;
}
public int wordCount()
{
return numOfWords;
}
public int uppercaseCount()
{
return uppercaseLetters;
}
public int digitCount()
{
return numOfDigits;
}
public int digitWordCount()
{
return digitWords;
}
public String getNoSpaceString()
{
return noSpaces;
}
public String getNoVowelString()
{
return noVowels;
}
public String getNoDigitWordString()
{
return noDigitWords;
}
public static void main(String[] args)
{
String input;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a line of text: ");
input = keyboard.nextLine();
StringProcessor str = new StringProcessor(input);
System.out.println("\nwords: " + str.wordCount());
System.out.println("uppercase: " + str.uppercaseCount());
System.out.println("digits: " + str.digitCount());
System.out.println("digit words " + str.digitWordCount());
System.out.println("line with no spaces: ");
}
}
For your first question, try finding out how to replace " " which is a whitespace into "" which is nothing (there are also string functions for this in case you've seen this in your classes already)
For your second question it might help to know that a string is an array of characters, again, in case you have seen string functions already you should probably look into the documentation you've gotten around that (or google it)
I hope you don't mind me not giving you straight up answers, seeing as this is a homeworks assignment you should probably just find it yourself, I just thought i'd get you on the right track.
First Question is how do i take a string I have and return it with no spaces. trim() only eliminates the first and last whitespace of the sentence(getNoSpaceString method).
String input = " Hello World ";
You can achieve this by:
String input2 = input;
input2 = input.replaceAll(" ", "");
Take a look here for more information
Second question:
Also I am trying to count the number of digit words my sentence has aka one is 1 digit word.
If you're trying to count number of words, then:
int words = input.trim().split(" ").length;
System.out.println("number of words: " + words);
Here's how split works
Let me know it this isn't what you're looking for for 2nd question
If you care less about time complexity, you can just use a for loop to iterate the string passed in. make another string to hold what to return, say, call it toReturn. in the for loop, all you need to do is to determine if this character is a " ". Use .charAt(i) to do so. if it's not, just attach it to the toReturn. after the for loop, you will have what you want to return.
For the first one, although there is a way to do it using library methods, given that it's a homework assignment, you should probably be looping through the characters one by one and then adding them to a new "result" string if they meet the criteria (i.e. not a space).
For the second one, there is a library method which you can use to split the string on spaces, which will give you a list of the words. You should have also created a list of each of the 10 "digit" words. Then you can iterate over your list of input words and see if they match any of the digit words.

how to count the number of words of the same(PALINDROME) in java

I'm a newbie Java Developer. I want to write code to count the number of palindrome words in the paragraph using Java.
The assumptions are : User can enter a paragraph containing as many sentences as possible. Each word is separated by a whitespace, and each sentence is separated by a period and The punctuation right before or after the word will be ignored, while the punctuation inside the word will be counted.
Sample Input : Otto goes to school. Otto sees a lot of animals at the pets store.
Sample output : Otto = 2 a = 1 Sees = 1
Read the file into your program, split the entries at every space and enter those into an arraylist. Afterwards, apply your palindrome algorithm onto each value in your arraylist and keep track of the words that were a palindrome and their occurences (for example a 2D array, or an arraylist with an object that holds both values).
When you've followed these steps, you should pretty much be there. More specific help will probably be given once you've shown attempts of your own.
Using Collections in java will reduce the programming effort
Algorithm :
Read the paragraph to a String variable
Split the String using StringTokenizer using token as ' '(space) and add each word to ArrayList (Set wont allow duplicates)
Write a method which return boolean (TRUE/ FALSE) value based on whether a given String is palindrome or not.
Define a Map to hold the values of palindrome String and number of times it is repeated.
If yes
add the String to Map with key as palindrome String and value as number of times
else
dont add the String to Map
Repeat the same logic until all the words are finished
Sample Code:
` public class StringPalindromeCalculator {
private Map<String, int> wordsMap = new HashMap<>();
private List<String> wordsList = new ArrayLiat<>();
private boolean isPalindrome(String inputString) {
// write String palindrome logic here
}
public Map<String, int> findPalindromeWords(String completeString) {
StringTokenizer wordTokenizer = new StringTokenizer(completeString, ' ');
while(wordTokenizer.hasMoreTokens()) {
wordsList.add(wordTokenizer.nextToken());
}
for(String word : wordsList) {
if(isPalindrome(word)) {
if(wordsMap.containsKey(word)) {
// increment the value of word
}
} else {
// put the word into Map and return the map value
}
}
return wordsMap;
}
}`
Hope this Helps :)
public class Palindrome {
int count = 0;
public static void main(String[] args) {
String a = "malayalammadyoydaraarasdasdkfjasdsjhtj";
Palindrome palindrome = new Palindrome();
palindrome.countPalin(a);
}
private int countPalin(String str) {
for (int i = 0; i < str.length() - 1; i++) {
char start = str.charAt(i);
String st = "";
st += start;
for (int j = i + 1; j < str.length(); j++) {
st += str.charAt(j);
StringBuffer rev = new StringBuffer(st).reverse();
if (st.equals(rev.toString()) && st.length() > 1) {
System.out.println(st.toString());
count++;
}
}
st = "";
}
System.out.println("Total Count : " + count);
return count;
}
}

Categories

Resources