Replace last two letters in Java - java

I am asking for help on this code that I am making, I want it to replace the last two letters. I am coding a program that will:
Replace four letter words with "FRED"
Replace the last two letters of a word that ends with "ed" to "id"
Finally, replace the first two letters if the word starts with "di" to "id"
I am having difficulty with the second stated rule, I know that for number 3 I can just use replaceFirst() and to use the length for the first rule, but I am not sure how to specifically swap the last two characters in the string.
Here is what I have so far:
package KingFred;
import java.util.Scanner;
public class KingFredofId2 {
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
String king = input.nextLine();
String king22 = new String();
String king23 = new String();
if(king.length()==4)
{
System.out.println("FRED");
}
String myString = king.substring(Math.max(king.length() - 2, 0));
if (myString.equals("ed"))
{
king22 = king.replace("ed", "id");
System.out.println(king22);
}
if(true)
{
king23 = king.replace("di", "id");
System.out.println(king23);
}
}
I am new to Stack Overflow, so please let me know how I can make my questions a little more understandable if this one is not easily comprehended.
Thanks.

There may be a way to more optimally combine the regular expressions, but this will work.
\\b - word boundary (white space, punctuation,etc).
\\b(?:\\w){4}\\b - four letter word
ed\\b - word ending with ed
\\bdi - word starting with di
replaceAll(regex,b) - replace what regex matches with string b
String s =
"Bill charles among hello fool march good deed, dirt, dirty, divine dried freed died";
s = s.replaceAll("\\b(?:\\w){4}\\b", "FRED")
.replaceAll("ed\\b", "id")
.replaceAll("\\bdi", "id");
System.out.println(s);
prints
FRED charles among hello FRED march FRED FRED, FRED, idrty, idvine driid freid F
RED

This is the most simplest way I could think to solve the second case of replacing the last two characters.
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a line or a word: ");
String s = sc.nextLine();
//getting the length of entered string
int length = s.length();
//initializing a new string to hold the last two characters of the entered string
String extract = "";
//checking if length of entered string is more than 2
if (length > 2) {
//extracting the last two letters
extract = s.substring(length - 2);
//updating the original string
s = s.substring(0, length - 2);
}
//checking if the last two characters fulfil the condition for changing them
if (extract.equalsIgnoreCase("ed")) {
//if they do, concatenate "id" to the now updated original string
System.out.println(s + "id");
} else {
//or print the originally entered string
System.out.println(s + extract);
}
}
}
I believe the comments are giving enough explanation and further explanation is not needed.

Related

How do i print the the first initial of a string and the last word of a string?

How do I print only the first letter of the first word and the whole word of the last? for example,
I will request username input like "Enter your first and last name" and then if I type my name like "Peter Griffin", I want to print only "P and Griffin". I hope this question make sense. Please, help. I'm a complete beginner as you can tell.
Here is my code:
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter your first and last name");
String fname=scan.next();
}
The String methods trim, substring, indexof, lastindexof, and maybe split should get you going.
This should do the work (typed directly here, so syntax errors might be there)
String fname=scan.nextLine(); // or however you would read whole line
String parts=fname.split(" ");
System.out.printf("%s %s",parts[0].substring(0,1),parts[parts.length-1]);
What you have to do next:
Check if there actually at least 2 elements in parts array
Check if first element is actually at least 1 char (no empty parts)
Check if there is actually line to read
Do your next homework yourself, otherwise you will not anything
I recommand you to watch subString(1, x) and indexOf(" ") to cut from index 1 to first space.
or here a other exemple, dealing with lower and multi name :
String s = "peter griffin foobar";
String[] splitted = s.toLowerCase().split(" ");
StringBuilder results = new StringBuilder();
results.append(String.valueOf(splitted[0].charAt(0)).toUpperCase() + " ");
for (int i = 1; i < splitted.length; i++) {
results.append(splitted[i].substring(0, 1).toUpperCase() + splitted[i].substring(1)+" ");
}
System.out.println(results.toString());

Java SE array help needed please

I need some help here with my java school work.
We were told to prompt the user for five words and from there determine the longest word of them and print to console the longest word as well as the number of characters in it.
Right now, I only manage to sort them out using the arrays by displaying the longest number of characters but i'm not sure how to display the word itself. Can someone please help me with it and please bear in mind i'm a total newbie in programming and my progress is still just in the basics so try to make it not too complicated for me please. In addition, feel free to pinpoint those redundant codes as I know I have quite a few. :) Thanks!
import java.util.Scanner;
import java.util.Arrays;
class LongestWord
{
public static void main(String [] args)
{
Scanner theInput = new Scanner(System.in);
System.out.println("Please enter your five words");
String fWord = theInput.next();
String sWord = theInput.next();
String tWord = theInput.next();
String fhWord = theInput.next();
String ffWord = theInput.next();
System.out.println(fWord + sWord + tWord + fhWord + ffWord);
int [] wordCount = new int[5];
wordCount[0] = fWord.length();
wordCount[1] = sWord.length();
wordCount[2] = tWord.length();
wordCount[3] = fhWord.length();
wordCount[4] = ffWord.length();
Arrays.sort(wordCount);
System.out.println(wordCount[4]);
}
}
You need to add all the string to array and iterate all of them.
sample:
String [] wordCount = new String[5];
wordCount[0] = fWord;
wordCount[1] = sWord;
wordCount[2] = tWord;
wordCount[3] = fhWord;
wordCount[4] = ffWord;
String longest = "";
longest = wordCount[0]; //get the first array of words for checking
for(String s : wordCount) //iterate to all the array of words
{
if(longest.length() < s.length()) //check if the last longest word is greater than the current workd
longest = s; //if the current word is longer then make it the longest word
}
System.out.println("Longest Word: " + longest + " lenght: " + longest.length());
result:
Please enter your five words
12345
1234
123
12
1
123451234123121
Longest Word: 12345 lenght: 5
You need to store all words into array and get the maximum value after sort according to its length.
String[] words = ....//Store all words into this array.
Arrays.sort(words, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o2.length() - o1.length();
}
});
System.out.println(words[0]);
or, if you use java-8 than you will get the result more easily,
String longWord=
Arrays.stream(words).max((o1, o2)->o1.length()-o2.length()).get();
Instead of putting lengths into an array, you should put all the words in an array and then loop them using for/while and check length of each string comparing with the previous one to record the max length string.
Or another way may be to read strings using loop and you can perform same logic of comparing lengths without using additional array.

How to show sentence word by word in a separate line

The sentence String is expected to be a bunch of words separated by spaces, e.g. “Now is the time”.
showWords job is to output the words of the sentence one per line.
It is my homework, and I am trying, as you can see from the code below. I can not figure out how to and which loop to use to output word by word... please help.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the sentence");
String sentence = in.nextLine();
showWords(sentence);
}
public static void showWords(String sentence) {
int space = sentence.indexOf(" ");
sentence = sentence.substring(0,space) + "\n" + sentence.substring(space+1);
System.out.println(sentence);
}
}
You're on the right path. Your showWords method works for the first word, you just have to have it done until there are no words.
Loop through them, preferably with a while loop. If you use the while loop, think about when you need it to stop, which would be when there are no more words.
To do this, you can either keep an index of the last word and search from there(until there are no more), or delete the last word until the sentence string is empty.
Since this is a homework question, I will not give you the exact code but I want you to look at the method split in the String-class. And then I would recommend a for-loop.
Another alternative is to replace in your String until there are no more spaces left (this can be done both with a loop and without a loop, depending on how you do it)
Using regex you could use a one-liner:
System.out.println(sentence.replaceAll("\\s+", "\n"));
with the added benefit that multiple spaces won't leave blank lines as output.
If you need a simpler String methods approach you could use split() as
String[] split = sentence.split(" ");
StringBuilder sb = new StringBuilder();
for (String word : split) {
if (word.length() > 0) { // eliminate blank lines
sb.append(word).append("\n");
}
}
System.out.println(sb);
If you need an even more bare bones approach (down to String indexes) and more on the lines of your own code; you would need to wrap your code inside a loop and tweak it a bit.
int space, word = 0;
StringBuilder sb = new StringBuilder();
while ((space = sentence.indexOf(" ", word)) != -1) {
if (space != word) { // eliminate consecutive spaces
sb.append(sentence.substring(word, space)).append("\n");
}
word = space + 1;
}
// append the last word
sb.append(sentence.substring(word));
System.out.println(sb);
Java's String class has a replace method which you should look into. That'll make this homework pretty easy.
String.replace
Update
Use the split method of the String class to split the input string on the space character delimiter so you end up with a String array of words.
Then loop through that array using a modified for loop to print each item of the array.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the sentence");
String sentence = in.nextLine();
showWords(sentence);
}
public static void showWords(String sentence) {
String[] words = sentence.split(' ');
for(String word : words) {
System.out.println(word);
}
}
}

Taking Portions of a String

I am working on an assignment which is confusing to me. It requires me to write a method called processName() that accepts a Scanner for the console as a parameter and prompts the user to enter a full name, then prints the last name first and then the first name last. For instance, if I enter "Sammy Jankins", it would return "Jankins, Sammy".
My plan is to go through the string with a for loop, find an empty space, and create two new strings out of it—one for the first and last name each. However, I am not sure if this is the right path and how to exactly do this. Any tips would be appreciated, thanks.
Here is what I have so far:
import java.util.*;
public class Exercise15 {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
processName(inputScanner);
}
public static void processName(Scanner inputScanner) {
System.out.print("Please enter your full name: ");
String name = inputScanner.next();
System.out.println();
int n = name.length();
String tempFirst;
for (int i = 0; i <= name.length()-1; i++) {
// Something that checks the indiviual characters of each string to see of " "exists
// Somethow split that String into two others.
}
}
}
Why don't you simply use String#split?
I won't solve this for you, but here what you should do:
split according to spaces.
Check if the size of the array is 2.
If so, print the second element then the first.
Tip: Viewing the API can save a lot of efforts and time.
Why not just to say:
String[] parts = name.split("\\s+");
String formattedName = parts[1] + ", " + parts[0];
I am leaving it for you as an exercise to support names that contain more than 2 words, for example "Juan Antonio Samaranch" that should be formatted as "Samaranch, Juan Antonio".
Using StringTokenizer will be more easier. Refer http://www.mkyong.com/java/java-stringtokenizer-example/ for example.
You can replace for loop with the following code:
int spaceIdx = name.indexOf(' '); // or .lastIndexOf(' ')
if (spaceIdx != -1) {
int nameLength = name.length();
System.out.println(name.substring(spaceIdx + 1) + ", " + name.substring(0, spaceIdx));
} else {
// handle incorrect input
}
I think you should also consider such inputs - Homer J Simpson
1.Use the StringTokenizer to split the string .This will be very helpful when you are trying to split the string.
String arr[]=new String[2]; int i=0; StringTokenizer str=new StringTokenizer(StringToBeSplited,"");
while(str.hasMoreTokens()){
arr[i++]=new String(str.nextToken());
}
System.out.println(arr[1]+" "+arr[0]);
That's all

Checking string formats in Java?

having problems doing something for a class I'm taking, since I missed a class or two. (I know it's looked down on to 'do someone's homework,' but I'm not looking for that.)
The assignment is as follows:
Write a program to do the following:
Prompt for input of someone's first, middle, and last name as a single string (using any combination of upper and lowercase letters).
Check to make sure the name was entered in the correct format (3 names separated by spaces). If the input is not correct, continue to request the input again until the format is correct.
Capitalize only the first letters of each part of the name, and print out the revised name.
Print out the initials for that name.
Print out the name in the format of: Lastname, Firstname, MI.
The major problem I'm having is the second part of the assignment; I got the first part, and I'm fairly sure I can manage through the rest, after I get the second set up.
import java.util.*;
public class TestStrings
{
public static void main(String[] args)
{
Scanner key = new Scanner(System.in);
String name;
System.out.print("Enter your name as 'First Middle Last': ");
name = key.nextLine();
}
}
From what I've gathered, I need to use the string.split? I'm not sure how to go about this, though, since I need to check to make sure there are three spaces, that aren't just right next to each other or something, such as "John(three spaces)Doe". I assume it's going to be some kind of loop to check through the input for the name.
The catch 22, is that I can't use arrays, or StringTokenizer. I must use the substring method.
Any help would be appreciated. Thanks. :D
To point you in the right direction to find the first name(since you cant use arrays):
String firstName = input.substring(0, input.indexOf(" "));
This will get you a substring from the start to the first space. If you research the indexOf and substring methods you should be able to go from there.
Look at the matches method if you know how to use regex. If not think about indexOf and substring methods.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
You can use the substring and the indexOf functions of String class to get what you need.
String#indexOf: Get's the position of a String inside a String.
String#substring: Get's a substring contained in a String.
String s = "Luiggi Mendoza J.";
String x;
while(s.indexOf(" ") > 0) {
x = s.substring(0, s.indexOf(" "));
System.out.println(x);
s = s.substring(s.indexOf(" ") + 1);
}
x = s;
System.out.println(x);
The program output will be:
Luiggi
Mendoza
J.
Use a while loop to continuously check whether user entered a string that consists of 3 parts which are seperated via a single space character ' ', then use split() function to verify 3 parts of string. By using substring() as demonstrated here you can get names seperately:
public static void main ( String [] args )
{
String name = "";
boolean ok = false;
Scanner key = new Scanner( System.in );
while ( !ok )
{
System.out.print( "Enter your name as 'First Middle Last': " );
name = key.nextLine();
try
{
if ( name.split( " " ).length == 3 )
ok = true;
}
catch ( Exception e ){ }
}
if ( ok )
{
String firstName = name.substring(0, name.indexOf(" "));
String middleName = name.substring(firstName.length()+1,
name.lastIndexOf(" "));
String surname = name.substring(middleName.length()+firstName.length()+2,
name.length());
}
}
This works using Pattern/Matcher and regexs. Also guards against strings of length 1 when adjusting case.
private static String properCase(String str) {
return str.substring(0, 1).toUpperCase()
+ (str.length() >= 1 ? str.substring(1).toLowerCase() : "");
}
public static void main(String[] args) {
boolean found = false;
do {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name as 'First Middle Last': ");
Pattern p = Pattern.compile("\\s*(\\w+?)\\s(\\w+?)\\s(\\w+)+\\s*");
Matcher m = p.matcher(scanner.nextLine());
found = m.find();
if (found) {
String first = m.group(1);
String middle = m.group(2);
String last = m.group(3);
String revised = properCase(first) + " " + properCase(middle)
+ " " + properCase(last);
System.out.println(revised);
System.out
.printf("%s %s %s.\n", properCase(last),
properCase(first), middle.substring(0, 1)
.toUpperCase());
}
} while (!found);
}

Categories

Resources