Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a substring(start, length) function?

I am trying to use a similar method to C#'s string.SubString(int start, int length).

But the substring function in Java is string.substring(int start, int end).

I want to be able to pass a start position and a length to the substring function.

Can anyone help me to solve this issue?

like image 275
James Meade Avatar asked Oct 07 '13 11:10

James Meade


People also ask

How do you find the length of a substring?

The substring begins with the character at the specified index and extends to the end of this string. substring(int beginIndex, int endIndex) : The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is (endIndex - beginIndex).

How do you get the first character of a string with a substring?

To get first character from String in Java, use String. charAt() method. Call charAt() method on the string and pass zero 0 as argument. charAt(0) returns the first character from this string.

How do substring () and substr () differ?

The difference between substring() and substr()The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .

What is length in substring?

Edit online. You can specify an asterisk as the second subscript value of the substring notation. This indicates that the length of the extracted string is equal to the length of the character string, less the number of characters before the starting character.


1 Answers

It could be something like

String mySubString(String myString, int start, int length) {
    return myString.substring(start, Math.min(start + length, myString.length()));
}

     

like image 95
Danstahr Avatar answered Nov 07 '22 00:11

Danstahr