2012-03-12 120 views
1

我正在编写一个Android应用程序,需要一些帮助。如何从字符串的开头修剪字符。 Android

我有一个字符串,其中包含一个URL。有时候,我会在url之前获得额外的文本,并且需要将其修剪掉。

我得到这个“一些很酷的sitehttp://somecoolsite.com”

而且希望这个“http://somecoolsite.com”

首先,我需要的,如果字符串不开始检测与http://然后如果不是,我需要修剪前面的所有内容http://

有没有简单的方法来做到这一点?

我可以做第一部分。

if (url.startsWith("http://") == false) { 
url.replace("", replacement) 
} 

任何帮助?

+0

你想看看[Javadoc文档字符串](http://developer.android.com/reference/java/lang/String.html)?这在Java中几乎是一样的。 – 2012-03-12 21:05:28

+1

您提供的代码与描述不匹配。 – aioobe 2012-03-12 21:05:49

回答

0

使用此:

if(inputURL.contains("http://") 
    inputURL = inputURL.substring(inputURL.indexOf("http://")); 
+0

我觉得我比我的回答更喜欢这个,尽管我可能会得到所有的肛门并且做一个临时索引变量来避免搜索字符串两次。 – 2012-03-12 21:09:26

+0

工作完全谢谢凯珊! – Doug 2012-03-12 21:29:57

2

要检查字符串http://开始你做

if (inputUrl.startsWith("http://")) { 
    ... 
} 

要向上剪掉前缀,直到http://第一次出现这样做

int index = inputUrl.indexOf("http://"); 
if (index != -1) 
    inputUrl = inputUrl.substring(index); 

API documentation for the String class应该提供您并提供您需要的所有信息。

+0

我喜欢这个答案比我的更好...... – 2012-03-12 21:11:52

0

另一种选择是:

inputUrl = inputUrl.replaceAll(".*http://","http://"); 

应该在所有条件下正常工作(但我相信正则表达式是有点低效率)。

0

请注意,提供的答案假设字符串将是小写的(没有“HTTP”或“HTTP”),并没有字符串包含https://开头