Substring Index Range

substring index range

0: U

1: n

2: i

3: v

4: e

5: r

6: s

7: i

8: t

9: y

Start index is inclusive

End index is exclusive

Javadoc link

Python get index range of all substring occurrences in string

You may leverage regular expressions, match.start() will returnt he start position and match.end() will provide the end position (the search is a literal string, so it must be re.escaped):

import re
def substring_range(s, substring):
for i in re.finditer(re.escape(substring), s):
yield (i.start(), i.end())

s = "abcdegfbcd"
substring = "bcd"
print([x for x in substring_range(s, substring)])

See the Python demo

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

You can use the substringWithRange method. It takes a start and end String.Index.

var str = "Hello, playground"
str.substringWithRange(Range<String.Index>(start: str.startIndex, end: str.endIndex)) //"Hello, playground"

To change the start and end index, use advancedBy(n).

var str = "Hello, playground"
str.substringWithRange(Range<String.Index>(start: str.startIndex.advancedBy(2), end: str.endIndex.advancedBy(-1))) //"llo, playgroun"

You can also still use the NSString method with NSRange, but you have to make sure you are using an NSString like this:

let myNSString = str as NSString
myNSString.substringWithRange(NSRange(location: 0, length: 3))

Note: as JanX2 mentioned, this second method is not safe with unicode strings.

C# improper result of index range expression

the resultString value should be a single space " "

No, it shouldn't.

The end of a range is exclusive, not inclusive. So for example, x[0..x.Length] will always return the whole string.

In your case, you're saying "everything before index 0" which is obviously "the empty string".

This is documented in (aside from other places) the documentation for Range.End:

Gets an Index that represents the exclusive end index of the range.

Java substring: 'string index out of range'

I"m guessing i'm getting this error
because the string is trying to
substring a Null value. But wouldn't
the ".length() > 0" part eliminate
that issue?

No, calling itemdescription.length() when itemdescription is null would not generate a StringIndexOutOfBoundsException, but rather a NullPointerException since you would essentially be trying to call a method on null.

As others have indicated, StringIndexOutOfBoundsException indicates that itemdescription is not at least 38 characters long. You probably want to handle both conditions (I assuming you want to truncate):

final String value;
if (itemdescription == null || itemdescription.length() <= 0) {
value = "_";
} else if (itemdescription.length() <= 38) {
value = itemdescription;
} else {
value = itemdescription.substring(0, 38);
}
pstmt2.setString(3, value);

Might be a good place for a utility function if you do that a lot...

String index out of range on space bar character

tl;dr: The exception occurs when you try to access a String at an index which exceeds it's length or is just not contained in the string (negative values).

Regarding your approach: It's usually not a good idea to prompt a name in full because people tend to input weird stuff or mix up the order. Better prompt for first and last name separately.

Assuming someone input his name with Firstname Lastname you wouldn't have to make such a substring mess, Java has some nice features:

    String name = "Mario Peach Bowser";
name = name.trim();
String[] parts = name.split(" ");
String lastname = parts[parts.length-1];
String firstname = name.replace(lastname, "").trim();
System.out.println("Hello "+firstname+", your last name is: "+lastname);

In this case I am using the trim() function to remove whitespaces at the start and end and just split the string when a white space occurs. Since people can have some middle names and stuff, I just replace the last name out of the raw input string, call trim() on it again and you have everything extracted.

If you really want a substring approach, the following would work:

    String lastname = name.substring(name.lastIndexOf(" ")).trim();
String firstname = name.substring(0,name.lastIndexOf(" ")).trim();

You usually don't store the index variables. But each variant would need some sort of error check, you can either use try{} and catch() or check the String before parsing.

How to fix string out of index range when customizing looping input() in python?

Solved!

Manage to avoid this issue by first checking if index range is met first before indexing.

while True:
line = input("> ")
if len(line) == 0 : # check if blank
print('please input something')
continue
if len(line) >= 2 : # check if index is in range
if line[1] == '#' :
continue
if line == "done" :
break
print(line)
print('Done!')

I actually want to trigger the condition if the position of '#' are in line[1] or in any line[] like " #HelloWorld" or " # Something". Thanks for the effort to write some method I can use, it helped me a lot.

Replacing index range in String with certain character - Python

For a simpler solution you could instead use rjust on the last 4 characters of the string, and fill it with # up to its original length:

s = 'TestName'
s[-4:].rjust(len(s), '#')

'####Name'

The problem with your function, is that you have to repeat the elements you want to use to replace as many times as replacements there will be. So you should do:

def maskify(cc):
c2 = cc.replace(cc[:-4], '#'*len(cc[:-4]))
return c2

String index out of range: 22 exception Java

When you make a string shorter, you reduce its length. But you're storing the initial string length, and using it as the loop bound.

Change i < lengthStr to i < str.length().


That fixes part of the problem, which is the IndexOfOfBoundsException. The other problem is that, having removed a character, you need to make sure that you check the next character fully too.

Consider the string aa:

  • You'd find the a at position 0, and remove it.
  • The next a is now at position 0; you'd skip over checking if it's a vowel
  • You'd move onto check position 1 next.

It would work if you string contained vowels in order of checking (e.g. aeiou), but not in general.

Having removed a character, you need to stop looping over other vowels, and then decrement i, in order to make sure that you check the character immediately following the one you removed:

    for (int i = 0; i < lengthStr; ++i) {
for (char vowel : VOWELS) {
if (str.charAt(i) == vowel) {
str = removeChar(str, i);
// Decrement i, so it gets incremented back to the
// same value on the next iteration of the outer loop.
--i;
break; // Break out of vowels loop.
}
}
}

However, this is a very inefficient way to approach the problem: every time you remove one vowel, you rebuild the rest of the string, including all the vowels you're going to subsequently remove.

If you want to do this without regex, the best way is to create a StringBuilder, and only add the non-vowels to it:

StringBuilder sb = new StringBuilder(lengthStr);
for (int i = 0; i < lengthStr; ++i) {
char c = str.charAt(i);
if (!isVowel(c) {
sb.append(c);
}
}
str = sb.toString();

where isVowel is a method which returns whether the given char is a vowel, e.g.

boolean isVowel(char c) {
return "aAeEiIoOuU".indexOf(c) >= 0;
}


Related Topics



Leave a reply



Submit