-1

I am facing a little challenge, here's what I've been trying to do.

Assuming I have these 2 variables

String word1 ="hello! hello!! %can you hear me%? Yes I can.";

And then this one

String word2 ="*Java is awesome* Do you % agree % with us?";

I want to be able to check if a variable contains a word that begins and ends with a particular symbol(s) like % and * that I am using and replace with; with '1' (one). Here's what I tried.

StringTokenizer st = new StringTokenizer(word1);


while(st.hasMoreTokens()){
  String block = st.nextToken();
 if( (block.startsWith("%") && block.endsWith("%") ||(block.startsWith("*") && block.endsWith("*")){
   word1.replace (block,"1");
}
}

//output
'hello!hello!!%canyouhearme%?YesIcan."

//expected
"hello! hello!! 1? Yes I can.";

It just ended up trimming it. I guess this is because of the delimiter used is Space and since the last % ends with %? It read it as a single block.

When I tried the same for word2  

I got "1Doyou%agree%withus?"

//expected 
"1 Do you 1 with us?"

And assuming I have another word like

String word3 ="%*hello*% friends";
I want to be able to produce 

 //output
 "1friends"

//expected
"11 friends"

Since it has 4-symbols 

Any help would be truly appreciated, just sharpening my java skills. Thanks.

aloy
  • 53
  • 6
  • I don't think you need tokens. You can use `charAt()` to check for your symbol and `replaceAll()` to replace it with 1 – Ayrton Mar 03 '19 at 01:15
  • 1
    How does `%*hello*%` translate to number `11`, and where does the 4 symbols come from? – jbx Mar 03 '19 at 01:16
  • @surendrapanday and with which counting system is that 4? `hello` has 5 characters... and not sure where the `*` disappeared, and how does that become 11? – jbx Mar 03 '19 at 01:24
  • @surendrapanday But that should result in "1", not "11", because he never said something like "%1%" should not be replaced, but another "1" appended to the existing one. – Tom Mar 03 '19 at 01:25
  • Okay, he refers to special symbols for special characters. `%**%` as four symbols, instead it should have been said special characters, that's where his presmption is wrong. – surendrapanday Mar 03 '19 at 05:43

3 Answers3

0

The question isn't clear (not sure about how %*hello*% somehow translates to 11, and didn't understand what you mean by Since it has 4-symbols), but wouldn't regular expressions work?

Can't you simply do:

String replaced = word1.replaceAll("\\*[^\\*]+\\*", "1")
                       .replaceAll("\\%[^\\%]+\\%", "1");
jbx
  • 21,365
  • 18
  • 90
  • 144
0

I would say your presumption that special characters will be replaced twice is wrong. Replace function only works with case when you are trying to replace occurance of String, which doesn't seem to work with special characters. Only replaceAll, seems to work in that case. In your code you are trying to replace special characters along with other strings inside that, so only replaceAll function will do so.

In other words, when replaceAll function is executed it checks occurance of special characters , and replaces it once. You wouldn't require effort of using StringTokenizer, which is part of Scanner library, it is only required if you are taking user's input. So, no matter what you do you would only see 1 friends instead of 11 friends , also , you wouldn't need if statement. Credit goes to jbx above for regex. Now, you could shorten your code like this, still bearing in mind that 1 is printed replacing whatever is inside special character is replaced by single number 1.

You will need if-statement to search , replaceAll, or replace function already searches in String you specify to search on, so that if-statement is redundant, it's just making code end up being verbose.

package object_list_stackoverflow;
import java.util.StringTokenizer;
public class Object_list_stackoverflow {
    public static void main(String[] args) {
        String word1 = "hello! hello!! %can you hear me%? Yes I can.";
        String word2 ="*Java is awesome* Do you % agree % with us?";
        String word3 ="%*hello*% friends";
        String regex = "\\*[^\\*]+\\*";
        String regex1= "\\%[^\\%]+\\%";       
  System.out.println(word3.replaceAll(regex, "1").replaceAll(regex1, "1")); 
       }   
    }

Also read similar question by going to : Find Text between special characters and replace string
You can also get rid of alphanumeric characters by looking at dhuma1981's answer: How to replace special characters in a string?

Syntax to replace alphanumerics in String :

replaceAll("[^a-zA-Z0-9]", "");
surendrapanday
  • 530
  • 3
  • 13
0

You can use a Regular Expression (RegEx) within the String.matches() method for determining if a string contains the specific criteria, for example:

if (word1.matches(".*\\*.*\\*.*|.*\\%.*\\%.*")) {
    // Replace desired test with the value of 1 here...
}

If you want the full explanation of this regular expression then go to rexex101.com and enter the following expression: .*\*.*\*.*|.*\%.*\%.*.

The above if statement condition utilizes the String.matches() method to validate whether or not the string contains text (or no text) between either asterisks (*) or between percent (%) characters. If it does we simply use the String.replaceAll() method to replace those string sections (between and including *...* and %...%) with the value of 1, something like this:

String word1 = "hello! hello!! %can you hear me%? Yes I can.";
if (word1.matches(".*\\*.*\\*.*|.*\\%.*\\%.*")) {
    String newWord1 = word1.replaceAll("\\*.*\\*|%.*%", "1");
    System.out.println(newWord1);
}

The Console window will display:

hello! hello!! 1? Yes I can.

If you were to play this string: "*Java is awesome* Do you % agree % with us?" into with the above code your console window will display:

1 Do you 1 with us?

Keep in mind that this will provide the same output to console if your supplied string was "** Do you %% with us?". If you don't really want this then you will need to modify the RegEx within the matches() method a wee bit to something like this:

".*\\*.+\\*.*|.*\\%.+\\%.*"

and you will need to modify the the RegEx within the replaceAll() method to this:

"\\*.+\\*|%.+%"

With this change there now must be text between both the asterisks and or the Percent characters before validation is successful and a change is made.

DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
  • Been studying regrex and all that u've posted from d link. Now, was able to achieve wat I wanted. Thank U. – aloy Mar 03 '19 at 14:52