For a project, I need to take a user input such as "I hate you" and I need to replace the word "hate" with "love". I can't use replace all.
I understand that I can use .indexOf and find the position of the word hate and then use concatenation to form a new sentence I'm just really confused on how to do that.
I'll show what I have below. Also can you guys keep in mind that I'm new to this site and programming. I'm not just here for a quick fix, I'm actually trying to learn this. I've been doing a lot of research and I can't seem to find an answer.
import java.util.Scanner;
public class ReplaceLab {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a line of text:");
String userInput = input.nextLine();
int position = userInput.indexOf("hello");
System.out.println("I have rephrased that line to read");
}
}
String.replace() will replace every ocurrance in your input String:
String userInput = input.nextLine();
String replaced = userInput.replace("hate", "love");// Here you have your new string
For example, "I hate to hate you" will become "I love to love you".
If only the first occurrence must be changed (making my example "I hate to love you") then alfasin comment is correct and String.replaceFirst() will get the job done.
If you have to use .indexOf()
String find = "hate";
String replace = "love";
int pos = userInput.indexOf(find);
int pos2 = pos + find.size();
String replaced = userInput.substring(0, pos) + " " + replace + " " + userInput.substring(pos2);
If you are doing this make sure to check that indexOf returns a valid number.
Related
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());
Edit Thanks for the help guys got it working now.
So I had a question to do to ask a user for first name and last name which I have done no problem but then I thought it's be good to expand the program so that if someone entered a surname like McCabe it would print T McC instead of TM. I'm just not sure about how to compare the first two letters of the secondname string to see if they are "mc".
public class InitialsAlt {
public static void main(String [] args){
Scanner keyboardIn = new Scanner (System.in);
String firstname = new String();
System.out.print (" Enter your first name ");
firstname = keyboardIn.nextLine();
String secondname = new String();
System.out.print (" Enter your second name ");
secondname = keyboardIn.nextLine();
if(secondname.charAt(0, 1)== "mc" ) {
System.out.print("Your initals are " + firstname.charAt(0)+ secondname.charAt(0,1,2));
}
else {
System.out.print("Your initals are " + firstname.charAt(0)+ secondname.charAt(0));
}
}
}
if (secondName.toLowerCase().startsWith("mc")) {
The easiest way is to use String.startsWith:
yourString.toLowerCase().startsWith("mc")
If you want to avoid lowercasing the entire string or creating a new object, only to check the first two characters:
yourString.length() >= 2
&& Character.toLowerCase(yourString.charAt(0)) == 'm'
&& Character.toLowerCase(yourString.charAt(1)) == 'c'
However, I would use the former solution as it is far more readable, and the performance hit from lowercasing the entire string is almost certainly negligible, unless you are doing this on quite large strings.
Use yourString.toLowerCase().indexOf("mc")==0. This will involve creation of a new String only once (Since indexOf() doesn't create a new one, using indexOf() would be better than using subString() here)
Use substring to get the first two letters, then convert to lowercase, then check to see if it equals:
String someString = "McElroy";
if (someString.subString(0,2).toLowerCase().equals("mc")) {
//do something
}
If its case insensitive you could use the Apache Commons Lang library:
if(StringUtils.startsWithIgnoreCase(secondname, "mc") {
// Do nice stuff
}
Otherwise, you can use:
if(StringUtils.startsWith(secondname.toLowerCase(), "mc") {
// Do nice stuff
}
So far I have been able to censor "cat", "dog" and "llama". Now I just need to make the exception of "Dogmatic" but cannot figure it out for the life of me. Below I have attached what I have so far. Please any suggestions will help really.
/* take userinput and determine if it contains profanity
* if userinput contains profanity, it will be filtered
* and a new sentence will be generated with the word censored
*/
keyboard = new Scanner(System.in);
System.out.println("Welcome to the Star Bulletin Board!");
System.out.println("Generate your first post below!");
String userInput = keyboard.nextLine();
userInput = userInput.toLowerCase();
if (userInput.indexOf("cat") != 15){
System.out.println("Your post contains profanity.");
System.out.println("I have altered your post to appear as: ");
System.out.println(userInput.replaceAll("cat", "***"));
}
else
System.out.println(userInput);
if (userInput.indexOf("dog") != -1){
System.out.println("Your post contains profanity.");
System.out.println("I have altered your post to appear as: ");
System.out.println(userInput.replaceAll("dog", "***"));
}
if (userInput.indexOf("llama")!= -1){
System.out.println("Your post contains profanity.");
System.out.println("I have altered your post to appear as: ");
System.out.println(userInput.replaceAll("llama", "*****"));
}
You can use a word boundary \\b. Word boundaries match the edges of a word, like spaces or punctuation.
if (userInput.matches(".*\\bdog\\b.*")) {
userInput = userInput.replaceAll("\\bdog\\b", "***");
}
This will censor "Don't be a llama." but it won't censor "Don't be dogmatic."
userInput.matches(".*\\bdog\\b.*") is a slightly better condition than indexOf/contains because it has the same match as the replacement. indexOf/contains would still show the message despite not censoring anything. .* matches any character (except typically new lines), optionally.
Note: this is still not a very effective way to filter profanity. See http://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/.
Use word boundaries. Take a look at the following code; it will print true for all cases except the last one:
String a = "what you there";
String b = "yes what there";
String c = "yes there what";
String d = "whatabout this";
System.out.println(Pattern.compile("\\bwhat\\b").matcher(a).find());
System.out.println(Pattern.compile("\\bwhat\\b").matcher(b).find());
System.out.println(Pattern.compile("\\bwhat\\b").matcher(c).find());
System.out.println(Pattern.compile("\\bwhat\\b").matcher(d).find());
You can combine all your bad words into a single regex like so:
Pattern filter = Pattern.compile("\\b(cat|llama|dog)\\b");
This is fine for simple cases, but for a more robust solution you probably want to use a library. Take a look at this question for more information.
I feel like my logic is decent here; I don't feel like I'm completely lost. However, I do know what exactly I'm doing wrong. I can always find the index of the start of the substring, but I can never find the full count (ex. 3,4,5,6) of the index of whatever word the user enters as the substring.
I have been struggling with this for about a week trying to figure out how to do it on my own, I can't get it right.
import java.util.Scanner;
public class midterm
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
String simplePhrase;
String portionPhrase;
int portionIndex;
int portionCount;
int portionIndexTotal;
System.out.println("Enter a simple phrase:");
simplePhrase = keyboard.nextLine();
int phraseLength = simplePhrase.length();
System.out.println("Phrase length:" +phraseLength);
System.out.println("Enter a portion of previous phrase:");
portionPhrase = keyboard.nextLine();
String portionPhraseSub = simplePhrase.substring(portionPhrase);
portionIndex = simplePhrase.indexOf(portionPhraseSub);
for (portionIndex; portionIndex <= portionPhrase; portionIndex++)
{
System.out.println("Portion phrase index:"+portionIndex);
}
}
}
I'm still confused on what you want. There are just two simple things to know and you seem to be making this more complicated than it needs to be.
To get the index of a single character, such as "c" in the word "acorn", you would do this:
String s = "acorn";
int cIndex = s.indexOf("c");
System.out.println("The index of c is: " + cIndex);
If you want to see if the string contains a chunk, you use the exact same method. So if we are looking at the word "acorn" again and you want to see where "orn" happens, you'd do this:
String s = "acorn";
int ornIndex = s.indexOf("orn");
System.out.println("The index of orn is: " + ornIndex);
Remember that indexes start from 0 in java, so the index of "a" in "acorn" is 0, of "c" is 1, of "o" is 2, and so on.
I hope that helps. Good luck :)
EDIT: You just commented this:
"I guess, my question is one i get my code to compile, How would I go about counting every single letter of my substring?"
I'll answer that as best as I can, though again, that still is a confusing question.
What do you even mean by count" every letter? If you want to break your word into individual letters, you can do something like this:
String s = "acorn";
char[] characters = new char[s.length()-1];
for(int i = 0; i < s.length() - 1; i++) {
char[i] = s.charAt(i);
}
But I have no clue why you'd want to do that...you can always access any character in a string at a given index with STRING.charAt(index), or if you want to have a String result, STRING.substring(index, index+1)
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