第N次出现一个字符和条件

时间:2017-04-11 10:16:44

标签: java string if-statement

我们说我们有两个字符串(ULR):

https://stackoverflow.com/questions/ask
https://web.whatsapp.com/

我需要写表达式,如:

如果在第3个斜杠(/)之后没有或第3个斜杠不存在那么

{
some operation
} else {
another action
}

请帮忙。

        List<String> list = new ArrayList<String>();

        while((str = in.readLine()) != null){
            list.add(str);
        }

    String[] stringArr = list.toArray(new String[0]);

    //copying and removing https from the list

     List<String> list2 =  new ArrayList<String>();
          Collections.addAll(list2, stringArr);
          Iterator<String> iter = list2.iterator();
          while(iter.hasNext()){
              if(iter.next().contains(https))
                  // here you should copy https lines to another file. 
                  iter.remove();
          } 

          String[] stringArr2 = list2.toArray(new String[0]);



        for (int i = 0; i<stringArr2.length; i++) {
            //condition for pure domain names.
            //else the action below



            System.out.println(getDomainName(stringArr2[i]) + "," + stringArr2[i] + "," + "U" +"," + number_of_doc + "," + today);
        }




    }

    public static String getDomainName(String url) throws URISyntaxException {
    URI uri = new URI(url);
    String domain = uri.getHost();
    return domain.startsWith("www.") ? domain.substring(4) : domain;
}





}

2 个答案:

答案 0 :(得分:2)

为什么你不分裂:

/

这个想法是:如果结果很好或等于3,那么用Guava's Splitter拆分你的字符串然后你的条件是正确的,否则不正确。

修改

或者像@biziclop在评论中提到的那样,您可以使用 Iterable<String> result = Splitter.on(CharMatcher.anyOf("/")). limit(4). split("https://stackoverflow.com/questions/ask"); if (Lists.newArrayList(result).size() > 3) { System.out.println(Lists.newArrayList(result).get(3)); }else{ System.out.println("NOTHING"); } ,例如:

https://stackoverflow.com/questions/ask
https://stackoverflow.com

<强>输入

questions/ask
NOTHING

输出

for(int i=0; i < A.Count(); i++) 
{
    A[i].Count = B[i].Count;
    A[i].CountType = B[i].CountType;
}

答案 1 :(得分:1)

您可以使用简单的正则表达式:

    String url = "https://web.whatsapp.com/";

    if(url.matches("\\w+://(\\w+.\\w+)+(.\\w+)*/(.+)"))
        System.out.println("Correct URL");
    else
        System.out.println("Incorrect URL");