0

this is the loop im executing

for(int i=0;i<str.length;i++){
    if (str[i]==strFind) {
        str[i]=strReplace;
        count++;
    }
}

The problem is that if the last word of the sentence has a period in some test cases and it doesn't have a period in some.And if i replace the word in the given manner. I cannot retain the period. Is there a simpler solution for this? Also, can replace all take a sting variable(strReplace-user input)?

Ali Bdeir
  • 4,151
  • 10
  • 57
  • 117
  • Comparison is not really my issue here.Replacing while maintaining the punctuation marks given by the user is the problem with my code. – Anubhav Agrawal Jul 06 '20 at 10:21
  • 1
    Does this answer your question? [replace String with another in java](https://stackoverflow.com/questions/5216272/replace-string-with-another-in-java) – Paul Jul 06 '20 at 10:32
  • @AnubhavAgrawal `if (str[i]==strFind) {` quite sure the comparison is an issue – jhamon Jul 06 '20 at 12:18

3 Answers3

0

You can make use of java's builtin String function, replace for your scenario.

int getReplacementCount(String sentence,String searchWord, String replacement){      
   int count = 0;
   while(true){
      String replacedSentence = sentence.replace(searchWord,replacement);
      if(replacedSentence.equals(sentence){
         return count;
      else {
         count++;
         sentence = replacedSentence;
      }
   }
        
}

Noushad
  • 384
  • 3
  • 11
0

Maybe the issue here is that you want to replace strings but you just watch and iterate over single characters of your string. You could use Apache Commons lang.

StringUtils.replace(text, searchString, replacement)
timguy
  • 2,063
  • 2
  • 21
  • 40
0

This can be done with a built in library in java.

You can simply use:

String str1 = "Hello world";

//usage: str1.replace(word_or_character to replace, replacement)
str1 = str1.replace(" ", "")
System.out.println(str1)

Output:

Helloworld
CodinGuy
  • 33
  • 1
  • 5