Java String.Indexof and Empty Strings

Java String.indexOf and empty Strings

The empty string is everywhere, and nowhere. It is within all strings at all times, permeating the essence of their being, yet as you seek it you shall never catch a glimpse.

How many empty strings can you fit at the beginning of a string? Mu

The student said to the teacher,

Teacher, I believe that I have found the nature of the empty string. The empty string is like a particle of dust, and it floats freely through a string as dust floats freely through the room, glistening in a beam of sunlight.

The teacher responded to the student,

Hmm. A fine notion. Now tell me, where is the dust, and where is the sunlight?

The teacher struck the student with a strap and instructed him to continue his meditation.

Java String IndexOf behaviour for empty string

If only there was some place where they document behaviour of methods.

indexOf(string)

Returns the index within this string of the first occurrence of the specified substring.
The returned index is the smallest value k for which:

this.startsWith(str, k)

startsWith(string)

true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise. Note also that true will be returned if the argument is an empty string or is equal to this String object as determined by the equals(Object) method.

indexOf empty string is zero. why?

The answer, fundamentally, is: Because that's how the function is specified to behave. And it makes sense, from a certain perspective.

The main bit related to returning 0 when you search for an empty string is this:

Return the smallest possible integer k not smaller than start such that k + searchLen is not greater than len, and for all nonnegative integers j less than searchLen, the code unit at index k + j within S is the same as the code unit at index j within searchStr; but if there is no such integer k, return the value -1.

Since the length of the search string is 0, both halves of that "and" are satisfied by k = 0: k + searchLen is not greater than the length of the string, and for all nonnegative integers less than the search length (there are zero), the code points match.

Or roughly speaking, in code:

function indexOf(searchString, position = 0) {
let s = String(this);
let searchStr = String(searchString);
let len = s.length;
let start = Math.min(Math.max(position, 0), len);
let searchLen = searchStr.length;
let k = 0;
while (k + searchLen <= len) {
if (s.substring(k, k + searchLen) === searchStr) {
break;
}
++k;
}
const found = k + searchLen <= len;
return found ? k : -1;
}

Since k + searchLen (0) is <= len (0), k (0)` is returned.

Live Example:

function indexOf(searchString, position = 0) {    let s = String(this);    let searchStr = String(searchString);    let len = s.length;    let start = Math.min(Math.max(position, 0), len);    let searchLen = searchStr.length;    let k = 0;    while (k + searchLen <= len) {        if (s.substring(k, k + searchLen) === searchStr) {            break;        }        ++k;    }    const found = k + searchLen <= len;    return found ? k : -1;}
console.log(indexOf.call("abcd", ""));

Java indexOf() returns 0

Because indexOf returns the first position (index) of its argument in the string. Strings in Java, like arrays and collections are zero-indexed, meaning that the index 0 describes the first item. Index 1 is the second item and index n describes the n+1th item. Many functions return the (invalid) index -1 (a "magic" value) to denote "not found" or "error".

The empty string is contained in every string multiple times. The first position where it can be found is at position 0. Think of it as: String s = "" + "We learn Java." (or even more verbose: s = "" + "W" + "" + "e" + "" + " " + "" + "l" + …).

String s = "We learn Java.";

System.out.println(s.indexOf("")); // -> 0
System.out.println(s.indexOf("W")); // 0
System.out.println(s.indexOf("e")); // -> 1
System.out.println(s.indexOf(" ")); // -> 2
System.out.println(s.indexOf("not found")); // -> -1

Why does '' (empty string) permeate all strings?

The spec says:

Return the smallest possible integer k not smaller than start such
that k+searchLen is not greater than len, and for all
nonnegative integers j less than searchLen, the character at
position k+j of S is the same as the character at position j
of searchStr; but if there is no such integer k, then return the
value -1.

That condition is fulfilled at position 0 because of vacuous truth: since you are searching the empty string, any statement you can think of will hold for every character, because it has no characters.

More formally, for any statement P, if S = ∅, P(x) holds ∀ x ∈ S.

Hello.indexOf() returns 0

First, if you were looking for a null character you would probably want to do (char)0 because "" is an empty string (no character).

Second, if Java uses a null character (they don't have to IIRC) then they hide it.

EDIT: Struck my third point because I'm not sure about it anymore.

SECOND EDIT: I looked it up, Java strings are not null terminated. They rely on the length field.

How can index be two things at once?

Because the empty string is a substring of every string. indexOf is specified to return the smallest index which matches the substring, so the index returned for any string will always be 0.

Why does contains() method find empty string in non-empty string in Java

An empty string occurs in every string. Specifically, a contiguous subset of the string must match the empty string. Any empty subset is contiguous and any string has an empty string as such a subset.

Returns true if and only if this string contains the specified sequence of char values.

An empty set of char values exists in any string, at the beginning, end, and between characters. Out of anything, you can extract nothing. From a physical piece of string/yarn I can say that a zero-length portion exists within it.

If contains returns true there is a possible substring( invocation to get the string to find. "aaa".substring(1,1) should return "", but don't quote me on that as I don't have an IDE at the moment.



Related Topics



Leave a reply



Submit