首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HTML字符串标记未被替换(Android)

问HTML字符串标记未被替换(Android)
EN

Stack Overflow用户
提问于 2015-07-15 10:25:16
回答 2查看 1K关注 0票数 2

我有以下HTML:

代码语言:javascript
复制
<p>Bla bla bla...</p>
<p><strong>4. others</strong></p>
<p> </p>

它包含一个随机的<p> </p>标签组合,需要在我的安卓应用程序中过滤掉。为此,我使用了以下Java代码:

代码语言:javascript
复制
String html = object.get("Content").toString(); // this is the HTML
html = html.replace("<p> </p>", "");
html = html.replace("<p></p>", "");
html = html.replace("<p><span></span></p>", "");
content.setText(Html.fromHtml(html));

但是,当我调试并在替换函数上放置一个断点时,它不会替换字符串。现在我有我不想要的无用的<p>标签。我该怎么解决这个问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-07-15 10:38:23

它包含一个随机的

标签组合,需要在我的Android应用程序中过滤掉。您需要分别替换它,。因为替换()函数可以工作case-sensitive和顺序字符串。所以,使用下面的代码

​

代码语言:javascript
复制
String html = object.get("Content").toString().trim(); // this is the HTML
html = html.replace("<p>", "");
html = html.replace("</p>", "");
html = html.replace("<span>", "");
html = html.replace("</span>", "");
content.setText(Html.fromHtml(html));

而不是替换()中的连接字符串

代码语言:javascript
复制
String html = object.get("Content").toString(); // this is the HTML
html = html.replace("<p> </p>", "");
html = html.replace("<p></p>", "");
html = html.replace("<p><span></span></p>", "");
content.setText(Html.fromHtml(html));

你会得到你想要的结果。

注意事项:但是,请记住,任何时候您都想替换任何字符/字符串,而不是按顺序替换为区分大小写的字符串。因为它给了你准确的结果。

票数 0
EN

Stack Overflow用户

发布于 2015-07-15 10:41:11

你这样做是不对的。

正确的方法: 1.使用StringBuffer而不是字符串。2.查找<的索引并将其放入变量中,如int startIdx 3,查找索引of >并将其放入变量( int endIdx 4 )中,然后使用StringBuffer的delete()并指定此startIdx和endIdx来删除startIdx标记。

这将从字符串中删除所有HTML代码。

Ok --根据你的评论,这是你怎么做的--

代码语言:javascript
复制
String replaceThis="<p></p>";
int len = replaceThis.length();
StringBuffer buff="your html string from which you want to replace";
int i;
while((i = buff.indexOf(replaceThis)!=-1)
{
    buff.delete(i,len-1);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31427802

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档