替换字符串部分

时间:2014-04-14 10:17:46

标签: java html string replace

这个主题已经在这里讨论了很多,但没有一个解决方案适合我。我想替换我从HTML获得的字符串的一部分。获取和显示HTML工作正常,但我无法删除字符串的任何部分。它的行为却没有找到它。

请看下面的代码:

public class Main extends Activity {

public static String URL = "";
public static String htmlString;
public TextView mainText;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);

    mainText = (TextView) findViewById(R.id.mainText);

    constructURL();
    getHtml();

    htmlString.replaceAll("<head>", "hulo");

    mainText.setText(htmlString);
}

public void getHtml() {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(URL);
        HttpResponse response = httpClient.execute(httpGet, localContext);
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(
                    response.getEntity().getContent()
                    )
            );
        String line = null;
        while ((line = reader.readLine()) != null){
            htmlString += line + "\n";
        }
    } catch (Exception e) {
    }
}

public void constructURL() {
    Time time = new Time();
    time.setToNow();
    String year = convertToString(time.year - 2000);
    String month = convertToString(time.month + 1);
    String monthDay = convertToString(time.monthDay);

    URL = "http://www.gymzl.cz/bakalari/suplovani_st/tr" + year + month + monthDay + ".htm";
}

public String convertToString(int value) {
    String text = "";
    if(value < 10) text = "0";
    text += String.valueOf(value);
    return text;
}
}

&#39; hulo&#39;替换似乎不起作用。

我很抱歉这么长的代码,但我已经尝试了所有的东西。

4 个答案:

答案 0 :(得分:2)

replaceAll不更新调用字符串,您需要将其分配回来。改变这个

htmlString.replaceAll("<head>", "hulo");

htmlString = htmlString.replaceAll("<head>", "hulo");

答案 1 :(得分:1)

 htmlString.replaceAll("<head>", "hulo");

返回替换字符串但不更改htmlString

所以直接这样做

mainText.setText(""+htmlString.replaceAll("<head>", "hulo"));

答案 2 :(得分:1)

调用replaceAll后,它将返回被替换的字符串。你需要再次将这个新字符串分配给某个对象

如下所示,再次将其分配给htmlString

htmlString = htmlString.replaceAll("<head>", "hulo");

答案 3 :(得分:0)

mainText.setText(htmlString.replaceAll("<head>", "hulo"));