Check string start with java

Java String startsWith() Method with examples

The startsWith() method of String class is used for checking prefix of a String. It returns a boolean value true or false based on whether the given string starts with the specified letter or word.

For example:

String str = "Hello"; //This will return true because string str starts with "He" str.startsWith("He");

Java String startsWith() method Examples

There are two variations of starsWith() method.

boolean startsWith(String str) : It returns true if the String str is a prefix of the String.

boolean startsWith(String str, index fromIndex) : It returns true if the String begins with str, it starts looking from the specified index “fromIndex”.

For example lets say that the value of the String str is “Hi there” and we are calling starsWith() method like this – str.startsWith(“there”, 3) then this will return true because we have provided the fromIndex value as 3. The method will start looking from index 3 and it will find the string from where it starts searching.

Читайте также:  Matplotlib python vertical line

Example 1: Checking prefix without fromIndex

This is a simple example where we have a string s and we are checking wether the string s starts with a particular word using startsWith() method.

Java String startsWith method example

Output:

Example 2: Checking prefix starting from an index

Let’s take an example where we are using both the variations of startsWith() method. As you can see that when we provided the fromIndex, the output changed. This is because it starts looking from the specified fromIndex.

  • If str.startsWith(«brown») then it is checking the prefix of this string: quick brown fox jumps over the lazy dog
  • If str.StartsWith(«brown», 6) then it is checking the prefix of this string: brown fox jumps over the lazy dog
public class StartsWithExample < public static void main(String args[]) < String str= new String("quick brown fox jumps over the lazy dog"); System.out.println("String str starts with quick: "+str.startsWith("quick")); System.out.println("String str starts with brown: "+str.startsWith("brown")); System.out.println("substring of str(starting from 6th index) has brown prefix: " +str.startsWith("brown", 6)); System.out.println("substring of str(starting from 6th index) has quick prefix: " +str.startsWith("quick", 6)); >>
String str starts with quick: true String str starts with brown: false substring of str(starting from 6th index) has brown prefix: true substring of str(starting from 6th index) has quick prefix: false

Example 3: Whether String starts with an empty string

An empty string is often referred as “” (no space between double quotes). We are checking whether every string has empty string as a prefix. We can simply check this by calling startsWith() method like this: str.startsWith(«») .

public class JavaExample < public static void main(String args[]) < String str = "Welcome to BeginnersBook"; // "" represents an empty string if(str.startsWith(""))< System.out.println("String has empty string as prefix"); >else < System.out.println("String doesn't have empty string as prefix"); >> >
String has empty string as prefix

Источник

startsWith() in Java

Java Course - Mastering the Fundamentals

The startsWith() method in Java is used to check if the string starts with the given prefix. The prefix that we want to check is also in the form of a string which is passed as a parameter to the function. The prefix can be a single character also. If the string starts with the given prefix, it returns true , or else it returns false .

Syntax of startsWith() in Java

The way of writing the syntax for the startsWith in Java is as follows:

The prefix parameter is compulsory. It checks whether this string(on which the function is called) starts with the given prefix.

The offset parameter is optional, and it checks the substring of a string starting from the given index. Therefore, syntax without offset is also syntactically correct:

Parameters of startsWith() in Java

The Java string startsWith method can take in two parameters.

  • String prefix (compulsory) — It is used to check whether «this» string(on which the function is called) starts with the given prefix. It is also a string.
  • int offset (optional)- It checks the substring of a string starting from the given index. It checks whether the prefix begins from the given index. This is an optional parameter. If not provided, the default value is considered 0 0 0 by the Java compiler.

Return value of startsWith() in Java

Return Type : boolean

  • Returns true if the string starts with the specified prefix(argument string).
  • Returns false if the string does not start with the specified prefix(argument string).

Exceptions of startsWith() in Java

If we pass null as an argument, it will throw the NullPointerException . It is so because null is not allowed as an argument.

Example of startsWith() in Java

Let’s discuss a simple example to understand startsWith() method better.

For the first output, the given string str starts with the argument string «Jav»; hence method returns true. It is not true for the second case, «java», because the method is case sensitive.

For the third and fourth outputs, offset is passed as the starting index to compare the prefix string with the given string.

We will discuss detailed examples in the ‘More Examples’ section of the article.

What is startsWith() in Java?

Have you wondered how actually the search results get rendered when we search names and text starting from certain letters?

We can achieve it effortlessly by using the startsWith() method. We can search using the keyword entered by the user by making it a parameter of the startsWith() method.

Let us now discuss the internal implementation for ‘startsWith()’ in Java. The below code shows how the method is implemented internally inside the library.

The above code helps to compare the string with the prefix (argument string) character by character, thus returning true or false. Note that internal implementation also takes into account for the offset to get the starting index to start the comparison.

More Examples

1) String startsWith(String str)

Explanation

Here the first startsWith() method checks if str starts with «S» and since it starts with «S», it prints true. This can be a use case where we are searching for the contact details of someone.

2) String startsWith(String str, int offset)

Before we proceed towards the example, it is important to know that indexing of strings is done from the 0th index, i.e., the 1st character has index 0, 2nd character has index 1.. and so on. It is described here as the offset parameter of this method revolves around the indexing concept. The offset is the index of the string also known as the start index from where we have to check.

String startsWithexample

Here in the above image, the indexing is shown for a string.

Explanation

String startsWith in java

Here the second argument in the startsWith method indicates the offset value or the index where the prefix has to be checked. In the first statement for startsWith() method, we have not mentioned any offset value, so the default offset value becomes 0 . In the second startsWith statement, it returns true as in the given string, «ri» is starting from the 2nd index. In the third startsWith statement, since «method» starts from the 7th index(whitespaces are counted as characters), false is printed. In the fourth startsWith statement, it returns true as «va» begins at 19th index.

If we want to check the sender’s name or email content in the inbox, we can use this method.

Explanation

Since the string str starts with «Hi», it prints true.

Conclusion

  • The startsWith() method is used to check if the string starts with the given prefix.
  • It returns a boolean value. If the string starts with the given prefix, it returns true, or else it returns false.
  • The Java string startsWith method can take in two parameters.
    • String prefix (compulsory)-It is used to check whether «this» string starts with the given prefix. It is also a string.
    • int offset (optional)- It checks the substring of a string starting from the given index.

    Источник

    How to check if a string starts with one of several prefixes?

    I want it to include startsWith Mon Tues Weds Thurs Friday etc. Is there a simple way to this when using strings? I tried || but it didn’t work.

    You mean you tried «Mon||Tues» etc.? Or did you use newStr4.startsWith(«Mon»)||newStr4.startsWith(«Tues») . ? Either way, please define «it didn’t work».

    10 Answers 10

    if (newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || . ) 

    Or you could use regular expression:

    if (newStr4.matches("(Mon|Tues|Wed|Thurs|Fri).*")) 

    @TheCrazyProgrammer Of course there is; matching via regular expressions is much more expensive than raw string method calls. Exact figures I cannot give, but this is the general consensus.

    Besides the solutions presented already, you could use the Apache Commons Lang library:

    if(StringUtils.startsWithAny(newStr4, new String[] )) < //whatever >

    Update: the introduction of varargs at some point makes the call simpler now:

    StringUtils.startsWithAny(newStr4, "Mon", "Tues". ) 

    No one mentioned Stream so far, so here it is:

    if (Stream.of("Mon", "Tues", "Wed", "Thurs", "Fri").anyMatch(s -> newStr4.startsWith(s))) 

    great (and up-to-date) answer. btw s -> newStr4.startsWith(s) can be replaced by newStr7::startsWith to be clearer

    if (newStr4.startsWith("Mon") || newStr4.startsWith("Tue") || newStr4.startsWith("Wed")) // . you get the idea . 

    A fancier solution would be:

    List days = Arrays.asList("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"); String day = newStr4.substring(0, 3).toUpperCase(); if (days.contains(day)) < // . >

    it is even simpler and more neat this way:

    let newStr4 = strr.split("2012")[0]; if (['Mon', 'Tues', 'Weds', 'Thurs', 'Friday'].some(word => newStr4.startsWith(word)))

    Of course, be mindful that your program will only be useful in english speaking countries if you detect dates this way. You might want to consider:

    Set dayNames = Calendar.getInstance() .getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()) .keySet(); 

    From there you can use .startsWith or .matches or whatever other method that others have mentioned above. This way you get the default locale for the jvm. You could always pass in the locale (and maybe default it to the system locale if it’s null) as well to be more robust.

    Источник

    Determine if string starts with letters A through I

    I’ve got a simple java assignment. I need to determine if a string starts with the letter A through I. I know i have to use string.startsWith(); but I don’t want to write, if(string.startsWith(«a»)); all the way to I, it seems in efficient. Should I be using a loop of some sort?

    If you’ll need to match both upper case and lower case characters, check out my post. Mark Byers matches only uppercase and we have a few posts matching lower case, just pick one (and update your question-post to clarify which one it is that you want).

    6 Answers 6

    You don’t need regular expressions for this.

    Try this, assuming you want uppercase only:

    char c = string.charAt(0); if (c >= 'A' && c

    If you do want a regex solution however, you can use this (ideone):

    Okay, this worked. but what exactly does the ^ mean, and .*$ mean? I know the [a-i] means a through i

    i mean, im asking what the ^ and .*$ means, and why i need it. I like to understand everything, as we haven’t learned this in my computer science class yet

    @Archey The means start of string, the . means any character, * means any number of times and $ is end of line. So, basically start of line followed by A-I followed by any character 0 or more times until the end of line.

    @Archey you can accept his answer if you want by clicking the check mark next to the two up and down arrows

    if ( string.charAt(0) >= 'A' && string.charAt(0)

    How about this for brevity?

    The above condition is filled, indexOf will return a value greater than -1 if the first character is found within the string. Right now it will act as if all letters accept BCDEGHI is correct.

    @Bill, this method obviously isn’t the best solution for a range check, for a set of characters, like «AEOIU», it works quite well.

    string.charAt(0) >= 'a' && string.charAt(0)  
    char c=string.toLowerCase().charAt(0); if( c >= 'a' && c  

    This makes it easy to extract it as a method:

    public static boolean startsBetween(String s, char lowest, char highest) < char c=s.charAt(0); c=Character.toLowerCase(c); //thx refp return c >= lowest && c

    which is HIGHLY preferred to any inline solution. For the win, tag it as final so java inlines it for you and gives you better performance than a coded-inline solution as well.

    Источник

Оцените статью