Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

I have a string (which is basically a file name following a naming convention) abc.def.ghi

I would like to extract the substring before the first . (ie a dot)

In java doc api, I can't seem to find a method in String which does that.
Am I missing something? How to do it?

like image 751
xyz Avatar asked Oct 07 '11 05:10

xyz


People also ask

How do I extract a particular substring from a string in Java?

You can extract a substring from a String using the substring() method of the String class to this method you need to pass the start and end indexes of the required substring.

How do you get a substring from a string before a character?

Use the substring() method to get the substring before a specific character, e.g. const before = str. substring(0, str. indexOf('_')); . The substring method will return a new string containing the part of the string before the specified character.

How do you cut a string after a specific character in Java?

Java – Split a String with Specific Character To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do you get a substring that comes after a certain character?

To get the substring after a specific character, call the substring() method, passing it the index after the character's index as a parameter. The substring method will return the part of the string after the specified character. Copied! We used the String.


11 Answers

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.

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
}
like image 59
Sam B Avatar answered Sep 28 '22 11:09

Sam B


You can just split the string..

public String[] split(String regex)

Note that java.lang.String.split uses delimiter's regular expression value. 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];
like image 44
Chad Schouggins Avatar answered Sep 28 '22 11:09

Chad Schouggins


look at String.indexOf and String.substring.

Make sure you check for -1 for indexOf.

like image 41
TofuBeer Avatar answered Sep 26 '22 11:09

TofuBeer


If your project already uses commons-lang, StringUtils provide a nice method for this purpose:

String filename = "abc.def.ghi";

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

see javadoc [2.6] [3.1]

like image 42
Max Fichtelmann Avatar answered Sep 26 '22 11:09

Max Fichtelmann


or you may try something like

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

like image 30
Umer Hayat Avatar answered Sep 25 '22 11:09

Umer Hayat


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
like image 24
Bohemian Avatar answered Sep 28 '22 11:09

Bohemian


In java.lang.String you get some methods like indexOf(): which returns you first index of a char/string. and lstIndexOf: which returns you the last index of String/char

From 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.

like image 25
Swagatika Avatar answered Sep 28 '22 11:09

Swagatika


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"

IF you have more than 3 String , so then it will look exactly like s2

like image 38
Vladi Avatar answered Sep 25 '22 11:09

Vladi


Here is code which returns a substring from a String until any of a given list of characters:

/**
 * 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);
}
like image 30
Random42 Avatar answered Sep 27 '22 11:09

Random42


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;
}
like image 36
Vinod Moyal Avatar answered Sep 25 '22 11:09

Vinod Moyal


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.

like image 27
Liam Botham Avatar answered Sep 29 '22 11:09

Liam Botham