简体   繁体   中英

How to replace a word based on its length?

All words having the given length wordLength in the string sentence must be replaced with the word myWord . All parameters come from user input and may vary. I have tried this way but it only returns the initial string with the initial words.

Here is my source code:

package main;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {

  public static void main(String[] args) throws Exception {
    String sentence = "";
    int wordLength = 0;
    String myWord = "";
    InputStreamReader is = new InputStreamReader(System.in);
    BufferedReader bis = new BufferedReader(is);

    System.out.println("Text input: ");
    sentence = bis.readLine();
    System.out.println("Word lenth to replace");
    wordLength = Integer.parseInt(bis.readLine());
    System.out.println("Word to replace to");
    myWord = bis.readLine();

    Text myText = new Text(myWord, sentence, wordLength);
    myText.changeSentence();
    System.out.println("New string" + myText.getSentence());
  }
}

class Text {

  private String mySentence;
  private int charNumber;
  private String wordToChange;
  private String newSentence = "1.";

  public Text(String wordToChange, String mySentece, int charNumber) {
    this.mySentence = mySentece;
    this.wordToChange = wordToChange;
    this.charNumber = charNumber;
  }

  public String getSentence() {
    return newSentence;
  }

  public void changeSentence() {
    int firstPos = 0;
    int i;
    for (i = 0; i < mySentence.length(); i++) {
      if (mySentence.charAt(i) == ' ') {
        if (i - firstPos == charNumber) {
          newSentence = newSentence.concat(wordToChange + " ");
          firstPos = i + 1;
        } else {
          newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
          firstPos = i + 1;
        }
      } else if (i == mySentence.length() - 1) {
        if (i - firstPos == charNumber) {
          newSentence = newSentence.concat(wordToChange + " ");
          firstPos = i + 1;
        } else {
          newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
          firstPos = i + 1;
        }
      }
    }
  }
}

I changed your code a little bit:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) {
        String sentence = "";
        int wordLenght = 0;
        String myWord = "";
        InputStreamReader is = new InputStreamReader(System.in);
        BufferedReader bis = new BufferedReader(is);
        try {
            System.out.println("Text input: ");
            sentence = bis.readLine();
            System.out.println("Word lenth to replace");
            wordLenght = Integer.parseInt(bis.readLine());
            System.out.println("Word to replace to");
            myWord = bis.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Text myText = new Text(myWord, sentence, wordLenght);
        System.out.println(myText.getChangeSentence());
    }
}

class Text {
    private String mySentence;
    private int charNumber;
    private String wordToChange;
    private String newSentence = "1.";

    public Text(String wordToChange, String mySentece, int charNumber) {
        this.mySentence = mySentece;
        this.wordToChange = wordToChange;
        this.charNumber = charNumber;
    }

    public String getChangeSentence() {
        String[] words = mySentence.split(" ");
        for(int i = 0 ; i < words.length ; i++) {
            if(words[i].length() == charNumber) {
                words[i] = wordToChange;
            }
        }
        for (String word : words) {
            newSentence += word + " ";
        }
        return newSentence;
    }
}

Input: This is a test word length: 2 word to replace: ii

output: This ii a test

As I can see the only separator of words that is currently considered to appear in the input text is a single white space " " . If that's true, then the changeSentence method can be quite short. There is no need to do parse the sentence character by characted. Having in mind that the white space is a separator, you can simply split the sentence by the characted " " and collect them as words. After that you can just iterate through words and replace ones that lenght matches given input characters number. After that, you can just join words together with the previously used separator and that's it.

Examples if you want to try with loops

public void changeSentence() {
    final String[] words = mySentence.split(" ");
    for (int i = 0; i < words.length; i++) {
        if (words[i].length() == charNumber) {
            words[i] = wordToChange;
        }
    }
    newSentence = String.join(" ", words);
}

or with regular expressions

public void changeSentence() {
    String regex = "\\b\\w{" + charNumber+ "}\\b";
    newSentence = mySentence.replaceAll(regex, wordToChange);
}

or with the stream API

public void changeSentence() {
    newSentence = Arrays.stream(mySentence.split(" "))
                .map(s -> s.length() == charNumber ? wordToChange : s)
                .collect(Collectors.joining(" "));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM