简体   繁体   English

在 java 中如何从字符串中得到 substring 直到字符 c?

[英]In java how to get substring from a string till a character c?

I have a string (which is basically a file name following a naming convention) abc.def.ghi我有一个字符串(基本上是一个遵循命名约定的文件名) abc.def.ghi

I would like to extract the substring before the first .我想在第一个之前提取 substring . (ie a dot) (即一个点)

In java doc api, I can't seem to find a method in String which does that.在 java doc api 中,我似乎无法在 String 中找到执行此操作的方法。
Am I missing something?我错过了什么吗? How to do it?怎么做?

The accepted answer is correct but it doesn't tell you how to use it. 接受的答案是正确的,但没有告诉您如何使用它。 This is how you use indexOf and substring functions together. 这是一起使用indexOf和substring函数的方式。

String filename = "abc.def.ghi";     // full file name
int iend = filename.indexOf("."); //this finds the first occurrence of "." 
//in string thus giving you the index of where it is in the string

// Now iend can be -1, if lets say the string had no "." at all in it i.e. no "." is found. 
//So check and account for it.

String subString;
if (iend != -1) 
{
    subString= filename.substring(0 , iend); //this will give abc
}

You can just split the string.. 您可以只拆分字符串。

public String[] split(String regex)

Note that java.lang.String.split uses delimiter's regular expression value. 请注意,java.lang.String.split使用分隔符的正则表达式值。 Basically like this... 基本上像这样

String filename = "abc.def.ghi";     // full file name
String[] parts = filename.split("\\."); // String array, each element is text between dots

String beforeFirstDot = parts[0];    // Text before the first dot

Of course, this is split into multiple lines for clairity. 当然,为了清楚起见,它分为多行。 It could be written as 它可以写成

String beforeFirstDot = filename.split("\\.")[0];

look at String.indexOf and String.substring . 看一下String.indexOfString.substring

Make sure you check for -1 for indexOf . 确保为indexOf检查-1。

If your project already uses commons-lang , StringUtils provide a nice method for this purpose: 如果您的项目已经使用commons-lang ,StringUtils为此提供了一个不错的方法:

String filename = "abc.def.ghi";

String start = StringUtils.substringBefore(filename, "."); // returns "abc"

see javadoc [2.6] [3.1] 参见javadoc [2.6] [3.1]

或者您可以尝试类似

"abc.def.ghi".substring(0,"abc.def.ghi".indexOf(c)-1);

How about using regex? 如何使用正则表达式?

String firstWord = filename.replaceAll("\\..*","")

This replaces everything from the first dot to the end with "" (ie it clears it, leaving you with what you want) 这会将所有从第一个点到最后一个点的内容都替换为“”(即清除该内容,为您提供所需的内容)

Here's a test: 这是一个测试:

System.out.println("abc.def.hij".replaceAll("\\..*", "");

Output: 输出:

abc

Here is code which returns a substring from a String until any of a given list of characters: 以下是从String返回子String直到给定字符列表中的任何一个的代码:

/**
 * Return a substring of the given original string until the first appearance
 * of any of the given characters.
 * <p>
 * e.g. Original "ab&cd-ef&gh"
 * 1. Separators {'&', '-'}
 * Result: "ab"
 * 2. Separators {'~', '-'}
 * Result: "ab&cd"
 * 3. Separators {'~', '='}
 * Result: "ab&cd-ef&gh"
 *
 * @param original   the original string
 * @param characters the separators until the substring to be considered
 * @return the substring or the original string of no separator exists
 */
public static String substringFirstOf(String original, List<Character> characters) {
    return characters.stream()
            .map(original::indexOf)
            .filter(min -> min > 0)
            .reduce(Integer::min)
            .map(position -> original.substring(0, position))
            .orElse(original);
}
public void getStrings() {
    String params = "abc.def.ghi";
    String s1, s2, s3;
    s1 = params.substring(0, params.indexOf("."));
    params = params.substring(params.indexOf(".") + 1);
    s2 = params.substring(0, params.indexOf("."));
    params = params.substring(params.indexOf(".") + 1, params.length());
    s3 = params;
}

the solution解决方案

s1="abc" s2="def" s3="ghi" s1="abc" s2="def" s3="ghi"

IF you have more than 3 String, so then it will look exactly like s2如果你有超过3 个字符串,那么它看起来就像 s2

I tried something like this,我试过这样的事情,

String str = "abc.def.ghi";
String strBeforeFirstDot = str.substring(0, str.indexOf('.'));
// strBeforeFirstDot = "abc"

I tried for my example, to extract all char before @ sign in email to extract and provide a username.我尝试以我的示例为例,在 email 中提取 @ 符号之前的所有字符以提取并提供用户名。

In java.lang.String you get some methods like indexOf(): which returns you first index of a char/string. 在java.lang.String中,您将获得一些类似于indexOf()的方法:该方法将返回第一个char / string索引。 and lstIndexOf: which returns you the last index of String/char 和lstIndexOf:返回字符串/字符的最后一个索引

From Java Doc: 从Java Doc:

  public int indexOf(int ch)
  public int indexOf(String str)

Returns the index within this string of the first occurrence of the specified character. 返回指定字符首次出现在此字符串中的索引。

This could help: 这可以帮助:

public static String getCorporateID(String fileName) {

    String corporateId = null;

    try {
        corporateId = fileName.substring(0, fileName.indexOf("_"));
        // System.out.println(new Date() + ": " + "Corporate:
        // "+corporateId);
        return corporateId;
    } catch (Exception e) {
        corporateId = null;
        e.printStackTrace();
    }

    return corporateId;
}
  private String getTextBefore(final String wholeString, String before){
   final int indexOf = wholeString.indexOf(before); 
   if(indexOf != -1){
       return wholeString.substring(0, indexOf);
   }
   return wholeString;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM