用字符串替换空白

时间:2020-07-03 12:51:00

标签: java for-loop replace

在此类中,目标是创建一个方法,以用单词“ like”替换字符串中的空白(“”)。这就是我到目前为止所得到的。我的问题是在方法中,如果我在主文件上执行此方法,则我的程序没有运行该方法,该如何解决呢?

public class Teen 
{
    private String firstName;
    private String lastName;
    private int grade;
    private Boolean textMessages;

   public Teen(String theFirstName, String theLastName, int theGrade, Boolean theTextMessages)
    {
        firstName = theFirstName;
        lastName = theLastName;
        grade = theGrade;
        textMessages = theTextMessages;
    }
    
    public String toString()
    {
        return firstName + " " + lastName + " is in grade " + grade + " and wants to send this 
        text:";
    }
    
    public String teenTalk(String text)
    {
   for(int i = 0; i<text.length(); i++)
    {
        String character = text.substring(i, i+1);
        if(character.equals(" "))
        {
            String front = text.substring(0, i);
            String back = text.substring(i+1);
            text = front + " like " + back;
        }
        if(!text.contains(" "))
        {
        text = text;    
        }
    }
        return text;
        
    }
    }



import java.util.Scanner;
public class TeenTester
{
    public static void main(String[] args)
    {
        Teen friend = new Teen("John", "Doe", 15, true);
        System.out.println(friend.toString());
        Scanner input = new Scanner(System.in);
        
        System.out.println("Enter the text message being sent:");
        String like = input.nextLine(); 
        System.out.println(friend.teenTalk(like));
    }
}

3 个答案:

答案 0 :(得分:1)

在迭代时替换字符串中的操作会造成问题。

使用字符串的replace方法

String alternative = text.replace(" ", " like ");

答案 1 :(得分:1)

为什么不最好使用String类中的replaceAll静态方法?

public String teenTalk(String text) {
     return text.replaceAll(" ", "like");
}

如果要使用substring方法保持逻辑,则还必须重新分配i索引的值,因为要迭代的String将会更改。

    private String teenTalk(String text) {
        if (!text.contains(" ")) {
            text = text;
        }
        for (int i = 0; i < text.length(); i++) {
            String character = text.substring(i, i + 1);
            if (character.equals(" ")) {
                String front = text.substring(0, i);
                String back = text.substring(i + 1);
                text = front + " like " + back;
                i = i + 5;
            }
        }
        return text;
    }

答案 2 :(得分:1)

如果要替换的空格,您当前的代码将导致无限循环,因为替换字符串也包含空格。替换时,您应将索引提前到替换的部分之外。请参阅下面的代码here

public static String teenTalk(String text)
{
    for(int i = 0; i<text.length(); i++)
    {
        String character = text.substring(i, i+1);
        if(character.equals(" "))
        {
            String front = text.substring(0, i);
            String back = text.substring(i+1);
            text = front + " like " + back;
            i += " like ".length() - 1;
        }
    }
    return text;
}

但是,这效率极低,最好使用String#replace

return text.replace(" ", " like ");