You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.
Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .
Check if a string contains a sub-string in C++ This find() method returns the first location where the string is found. Here we are using this find() function multiple times to get all of the matches. If the item is found, this function returns the position. But if it is not found, it will return string::npos.
Or if you need to set the value of found:
found = Value1.StartsWith("abc")
Edit: Given your edit, I would do something like:
found = Value1.Substring(0, 5).Contains("abc")
I would use one of the of the overloads of the IndexOf method
bool found = Value1.IndexOf("abc", 0, 7) != -1;
shorter version:
found = Value1.StartsWith("abc");
sorry, but I am a stickler for 'less' code.
Given the edit of the questioner I would actually go with something that accepted an offset, this may in fact be a Great place to an Extension method that overloads StartsWith
public static class StackOverflowExtensions
{
public static bool StartsWith(this String val, string findString, int count)
{
return val.Substring(0, count).Contains(findString);
}
}
if (Value1.StartsWith("abc")) { found = true; }
Use IndexOf is easier and high performance.
int index = Value1.IndexOf("abc");
bool found = index >= 0 && index < x;
This is what you need :
if (Value1.StartsWith("abc"))
{
found = true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With