【问题标题】:Replacing String parts更换弦乐部件
【发布时间】:2014-05-28 06:19:29
【问题描述】:

这个话题已经在这里讨论了很多,但没有一个解决方案对我有用。我想替换从 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;
}
}

“hulo”替换似乎不起作用。

很抱歉这么长的代码,但我已经尝试了一切。

【问题讨论】:

    标签: java html string replace


    【解决方案1】:

    replaceAll 不会更新调用字符串,您需要重新分配它。改变这个

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

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

    【讨论】:

    • 谢谢。我应该读过JavaDOC。对于那个很抱歉。我会尽快将此标记为 anwser。
    • @ViliX 没问题,有时会发生。很高兴帮助:-)
    【解决方案2】:
     htmlString.replaceAll("<head>", "hulo");
    

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

    所以直接这样做

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

    【讨论】:

      【解决方案3】:

      调用 replaceAll 后,会返回替换后的字符串。您需要再次将此新字符串分配给某个对象

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

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

      【讨论】:

        【解决方案4】:
        mainText.setText(htmlString.replaceAll("<head>", "hulo"));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-29
          • 1970-01-01
          • 1970-01-01
          • 2012-07-19
          • 1970-01-01
          相关资源
          最近更新 更多