removing characters from string using a method in java - java

I'm trying to write a method to take in a string as a parameter and remove all whitespaces and punctuation from it so this is my idea of how to do that..
import java.util.*;
public class Crypto {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Please insert the text you wish to encrypt: ");
String text = input.nextLine();
text = normalizeText(text);
System.out.println(text);
}
public static String normalizeText(String s){
s.replace(" ","");
s.replace("(","");s.replace(")","");s.replace(".","");
s.replace(",","");s.replace("?","");s.replace("!","");
s.replace(":","");s.replace("'","");s.replace("\"","");
s.replace(";","");
s.toUpperCase();
return s;
}
}
Now , I only added the text = normalize Text(text); and then printed it because it wouldn't print it to the screen without it( even though in some methods the return would actually show an output on the screen)
anyway, even this change didn't help because it doesn't remove anything from the string taken in by the method it prints out the exact same string.. any help?
Thanks in advance . :)

Problem in your code is, you haven't assigned back the new string that got generated after s.replace(":",""); Remember, strings are immutable so the change by replace method will not apply to the string object on which you call the method.
You should have written,
s = s.replace(":", "")
Instead of your tedious method normalizeText you can write your method like this,
public static String normalizeText(String s){
return s.replaceAll("[ ().,?!:'\";]", "").toUpperCase();
}

You need to make assignments to the string after each replacement has been made, e.g.
public static String normalizeText(String s) {
s = s.replace(" ", "");
s = s.replace("(","");
// your other replacements
s = s.toUpperCase();
return s;
}
But note that we can easily just use a single regex to handle your replacement logic:
public static String normalizeText(String s) {
s = s.replaceAll("[().,?!:'\"; ]", "").toUpperCase();
return s;
}

Related

How to remove every sequence of "()" in a string in java?

I'm trying to remove every sequence of () in my string.
For example my String is:
String a = "() a)";
And I want it to become
" a)"
When I tried this it gave me an infinite loop
public static String removeParentheses(String s) {
while (s.contains("()")) {
s = s.replaceAll("()", "");
}
return s;
}
String replaceAll method require regexp in parameter. In your case you provide empty group. To use string as parameter you can use replace method like:
public static void main(String[] args) {
String toChange = "asa()assaa()ass()asa()";
String result = toChange.replace("()", "");
assert Objects.equals(result, "asaassaaassasax");
}
Or change the regexp to correct form using \ character in way:
public static void main(String[] args) {
String toChange = "asa()assaa()ass()asa()";
String result = toChange.replaceAll("\\(\\)", "");
assert Objects.equals(result, "asaassaaassasax");
}
According the documentation of String.replaceAll, the first argument is a regular expression.
This means () is not being treated literally, it's being treated as an empty capture group, which effectively matches nothing. I think what you're looking for is the normal String.replace method. I'm aware that the names of these methods seem to imply that replace only replaces one instance while replaceAll replaces all of them, but this is not the case.
public static String removeParentheses(String s) {
return s.replace("()", "");
}
JDoodle deomonstrating code above
If for some reason you would like to continue using replaceAll instead, you can dynamically escape the pattern using Pattern.quote.
public static String removeParentheses(String s) {
String pattern = Pattern.quote("()");
return s.replaceAll(pattern, "");
}
JDoodle demonstrating code above

Eclipse JAVA String reverse - reversing 1 word which is pre-declared [duplicate]

This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 5 years ago.
Like to know how to reverse a string value (1 word) which is pre-declared in the program. I mean not using user input or scanner.
Like to reverse a word "TRAIN" which is pre-declared in the program.
Have tried the below program but no results and no error also.
// QUERY PROGRAM NOT RUNNING - NO RESULT, NO ERROR.
// STRING REVERSE PROGRAM USING ARRAY
package abnpackage;
class Play {
void REVERSE (){
String [] INPUT_WORD = {"T","R","A","I","N"};
int Q;
for(Q=INPUT_WORD.length-1; Q>=0; Q=Q--);
System.out.print ("REVERSE VALUE" + INPUT_WORD[Q]);
}
public static void main(String[]args){
Play PL = new Play();
PL.REVERSE();
}
}
Problem in Q=Q-- and ; symbol after for cylce. Try this:
class Play{
void REVERSE (){
String [] INPUT_WORD = {"T","R","A","I","N"};
int Q;
for(Q=INPUT_WORD.length-1; Q>=0; Q--) {
System.out.print(INPUT_WORD[Q]);
}
}
public static void main(String[]args){
Play PL = new Play();
PL.REVERSE();
}
}
I'd like to offer a few suggestions.
Indent your code. It not only makes it easier for you to follow, but makes it easier for others to read your code.
Naming conventions. Use Title case for classes, camelCase for both variables and methods, and UPPER_CASE for constants.
Strings and characters. A String can be decomposed into an array of characters with the built-in method, String.toCharArray(). A character array is mutable, so is often used as an intermediate structure when converting a String from one state to another for tasks like ciphers or interview problems.
Encapsulation. If you can make your methods use only what is submitted to them through their method signature, and only output their return value, it's usually best. Prefer passing values over referencing constants in your utility methods to make them easier to follow.
package abnpackage;
class Play {
private static final String INPUT_WORD = "TRAIN";
private String reverse(String word) {
char[] letters=word.toCharArray();
StringBuilder sb=new StringBuilder();
for (int q=letters.length-1; q>=0; q--) {
sb.append(letters[q]);
}
return sb.toString();
}
public static void main(String[]args) {
Play play = new Play();
System.out.println("REVERSE VALUE: " + play.reverse(INPUT_WORD));
}
}
class Play {
void REVERSE() {
String[] INPUT_WORD = {"T", "R", "A", "I", "N"};
String[] OUTPUT_WORD =new String[INPUT_WORD.length];
int length = INPUT_WORD.length;
int i = 0;
while(--length>=0){
OUTPUT_WORD[i++] = INPUT_WORD[length];
}
System.out.println(Arrays.toString(OUTPUT_WORD));
}
public static void main(String[] args) {
Play PL = new Play();
PL.REVERSE();
}
}
Your code is entering an endless loop because of the assignment "Q=Q--"
for(Q=INPUT_WORD.length-1; Q>=0; Q=Q--);
It should instead be
Q--
without a semicolon at the end.
If the code runs successfully, it will print the words "REVERSE VALUE" repeatedly prior to printing each character in reverse.
System.out.print ("REVERSE VALUE" + INPUT_WORD[Q]);
So you will want to keep the text in reverse prior to printing the whole statement at the end of the execution of the for loop.
What is the reason to use array of String instead of just String? Since it's not mentioned as a requirement, I'm suggesting the following as an alternative solution:
public class Play {
static void reverse(){
String inputWord = "TRAIN";
char[] toStrArray = inputWord.toCharArray();
char[] revisedInput = new char[inputWord.length()];
int i = 0;
for(int q=toStrArray.length-1; q>=0; q--){
revisedInput[i]=toStrArray[q];
i++;
}
System.out.print ("REVERSE VALUE: " + new String(revisedInput));
}
public static void main(String[]args){
//Play PL = new Play();
//PL.REVERSE();
reverse();
}
}
Note: You can declare the method reverse as a static method. By doing this you don't have to create an object before calling it. Hope this helps.

Java - Insert String into another String after string pattern?

I'm trying to figure out how to insert a specific string into another (or create a new one) after a certain string pattern inside the original String.
For example, given this string,
"&2This is the &6String&f."
How would I insert "&l" after all "&x" strings, such that it returns,
"&2&lThis is the &6&lString&f&l."
I tried the following using positive look-behind Regex, but it returned an empty String and I'm not sure why. The "message" variable is passed into the method.
String[] segments = message.split("(?<=&.)");
String newMessage = "";
for (String s : segments){
s.concat("&l");
newMessage.concat(s);
}
System.out.print(newMessage);
Thank you!
You can use:
message.replaceAll("(&.)", "$1&l")
(&.) finds pattern where an ampersand (&) is followed by anything. (&x as you've written).
$1&l says replace the captured group by the captured group itself followed by &l.
code
String message = "&2This is the &6String&f.";
String newMessage = message.replaceAll("(&.)", "$1&l");
System.out.println(newMessage);
result
&2&lThis is the &6&lString&f&l.
My answer would be similar to the one above. It just this way would be reusable and customizable in many circumstances.
public class libZ
{
public static void main(String[] args)
{
String a = "&2This is the &6String&f.";
String b = patternAdd(a, "(&.)", "&l");
System.out.println(b);
}
public static String patternAdd(String input, String pattern, String addafter)
{
String output = input.replaceAll(pattern, "$1".concat(addafter));
return output;
}
}

Remove double tag from string

I have a String look like this :
<start> <start> some sentence <stop> is a sentence <stop>
How I can make those String something like this :
<start> some sentence is a sentence <stop>
So far I'm using regex to remove the double start first
string.replace("<start> <start>","<start>");
but I'm still stuck at removing the middle stop tag.
Can do like below replaceFirst is String class method which replaces the first substring of this string that matches the given regular expression with the given replacement.
String finalResult=string.replaceFirst("<start>", "" ).replaceFirst("<stop>", "" )
If you are sure about Start and Stop Tags in Starting & Ending. You can also hardcode them manually and remove all the tags in-between.
public class myclass {
public static void main(String[] args) {
String x = "<start> <start> some sentence <stop> is a sentence <stop>";
String finalResult="<start>"+x.replaceAll("<[^>]+>", "")+"<stop>";
System.out.println(finalResult);
}
}
One way, you can just remove all of the instances and then fix the String how you want it:
private static final String START = "<start>";
private static final String STOP = "<stop>";
private boolean containsKeywords(final String string) {
return string.contains(START) ||
string.contains(STOP);
}
private String stripAllStartStop(final String string) {
string.replaceAll(START, "");
string.replaceAll(STOP, "");
}
private addStartStop(final String string) {
StringBuilder sb = new StringBuilder();
sb.add(START);
sb.add(string);
sb.add(STOP);
return sb.build();
}
/**
* Cleanup the sequence of START and STOP tokens in a String.
*/
public String sanitizeString(final String string) {
if (containsKeywords(string)) {
return addStartStop(stripAllStartStop(string));
}
}
The better, cleaner, and more extensible way is similar, but using StrSubstitutor using a lookup Map for the replacements.
The stop you want to remove is wrapped by empty spaces to the right AND left use that as criteria to remove the one you need..
string.replace(" <stop> ","");

JAVA - Making Constructors, Calling Sets, and Replacing Chars in a String using set Classes

In Java, where should I aim (I enjoy figuring it out myself) to get, with sample data:
I am Sam I am a
the output:
I am Sam I am - letter to remove a
I m Sm I m
Basically, it is to "Remove all instances of the specified removal letter from the original sentence"
As this is for a class, I am limited with what I can do. For this assignment I am stuck with the given classes/constructors and am not allowed to make any more unless it is noted, which in my case, is to create another constructor class; Anyway, that has been the real challenge as it is hard to get help (No matter how many times I've googled!) with it being so specific and I new to the language.
Here is what I was given:
import static java.lang.System.*;
public class LetterRemover
{
private String sentence;
private char lookFor;
public LetterRemover()
{
//call set
}
//add in second constructor
public void setRemover(String s, char rem)
{
sentence = s;
lookFor = rem;
}
public String removeLetters()
{
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
This is what I've done so far:
import java.util.Scanner;
import static java.lang.System.*;
public class LetterRemover
{
private String sentence;
private String lookFor;
public LetterRemover()
{
//I am not sure what this means
}
//add in second constructor
public void setRemover(String s, String rem)
{
sentence = s;
lookFor = rem;
}
public String removeLetters()
{
sentence = sentence.replaceAll(lookFor,"");
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
I tried changing the char to a string for the "lookfor" to use the replace all method which seemed after a lot of research and the best way to get the letters out.
Is there any noticeable mistakes and where should I look to fix them? I do not really want the right code, or for anyone to "do" the work for me. I really want to try and figure it out. But I need a little help in pointing in the right direction to get my desired output :)
Let me know if there is any other details or whatnot, this is also , this is also my first time using the site. There were many similar questions to this, but as I really am a beginner I struggled to understand people's explanations
--Edit--
Moving to my runner class, this is what I wrote, trying to get for the desired output. I am not really sure how to deal with output as I really have just started learning to write them myself.
I keep getting a void error though:
import static java.lang.System.*;
public class LetterRemoverRunner
{
public static void main( String args[] )
{
LetterRemover test = new LetterRemover
(test.setRemover("I really want dumplings","l"));
}
}
Try the below code and confirm this is what your requirement is.
LetterRemoverRunner.java
public class LetterRemoverRunner {
public static void main(String args[])
{
LetterRemover test = new LetterRemover ();
test.setRemover("I really want dumplings","l");
System.out.println(test.toString());
System.out.println("Removed :"+test.removeLetters());
}
}
LetterRemover.java
public class LetterRemover
{
private String sentence;
private String lookFor;
public LetterRemover()
{
//I am not sure what this means
}
public void setRemover(String s, String rem)
{
this.sentence = s;
this.lookFor = rem;
}
public String removeLetters()
{
sentence = sentence.replaceAll(lookFor,"");
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
I'm pleased you suggested you don't want the answer - much better way to learn!
I'm not sure you've understood constructors yet. You're line:
LetterRemover test = new LetterRemover
(test.setRemover("I really want dumplings","l"));
Is going to give you a null pointer error because it's calling setRemover on test before test has been constructed. You should be constructing the object with its sentence and lookFor values before calling setRemover.
Here are some things you might want to look at:
The String.indexOf method will look for a certain character or string and tell you where to find it (or if it isn't in the string at all).
The String.substring method allows you to take part of a string using string positions
You can build a new string by concatenating substrings together
Using a while loop you can continue using indexOf until the target cannot be found.
As you've pointed out, you can also use one of the replace methods to replace the target with "".

Categories

Resources