How to Take a Substring to the First Index of a Character

How do I take a substring to the first index of a character?

Something like this should work:

myMessage.substringToIndex(myMessage.characters.indexOf(" ")!)

Note that in this code I force unwrapped the optional. If you're not guaranteed to have that space in the string, it might make more sense to have the index in a optional binding.

With optional binding, it would look something like this:

if let index = myMessage.characters.indexOf(" ") {
let result = myMessage.substringToIndex(index)
}

In java how to get substring from a string till a character c?

look at String.indexOf and String.substring.

Make sure you check for -1 for indexOf.

How to grab substring before a specified character in JavaScript?

var streetaddress = addy.substr(0, addy.indexOf(',')); 

While it's not the best place for definitive information on what each method does (mozilla developer network is better for that) w3schools.com is good for introducing you to syntax.

Java: Getting a substring from a string starting after a particular character

String example = "/abc/def/ghfj.doc";
System.out.println(example.substring(example.lastIndexOf("/") + 1));

How can I find the first occurrence of a sub-string in a python string?

find()

>>> s = "the dude is a cool dude"
>>> s.find('dude')
4

How can i get the index of the first and last char in string?

You can use String.indexOf(String str) function which will return starting indexof the "CAD". Then add one less then the length of String to find in the returned value, that will be your last character index of "CAD".

Something like this:

String value = "161207CAD140000,0";
String str = "CAD";
String datePart = value.substring(0, value.indexOf(str)); // for finding the date part
String amountStr = value.substring(value.indexOf(str) + str.length()); //for finding the amount part
System.out.println(datePart +" "+amountStr);`

Now suppose the String "CAD" is dynamic and you don't know what value it will have, in that case its better to use regex. Please see below code snippet:

String value = "161207CAD140000,0";
String patt = "[\\d,]+";
Pattern pattern = Pattern.compile(patt);
Matcher matcher = pattern.matcher(value);

while(matcher.find()){

System.out.println(matcher.group());
}

If any question let me know in comments. Hope it helps.

Index of a substring in a string with Swift

edit/update:

Xcode 11.4 • Swift 5.2 or later

import Foundation

extension StringProtocol {
func index<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> Index? {
range(of: string, options: options)?.lowerBound
}
func endIndex<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> Index? {
range(of: string, options: options)?.upperBound
}
func indices<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Index] {
ranges(of: string, options: options).map(\.lowerBound)
}
func ranges<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Range<Index>] {
var result: [Range<Index>] = []
var startIndex = self.startIndex
while startIndex < endIndex,
let range = self[startIndex...]
.range(of: string, options: options) {
result.append(range)
startIndex = range.lowerBound < range.upperBound ? range.upperBound :
index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
}
return result
}
}

usage:

let str = "abcde"
if let index = str.index(of: "cd") {
let substring = str[..<index] // ab
let string = String(substring)
print(string) // "ab\n"
}


let str = "Hello, playground, playground, playground"
str.index(of: "play") // 7
str.endIndex(of: "play") // 11
str.indices(of: "play") // [7, 19, 31]
str.ranges(of: "play") // [{lowerBound 7, upperBound 11}, {lowerBound 19, upperBound 23}, {lowerBound 31, upperBound 35}]

case insensitive sample

let query = "Play"
let ranges = str.ranges(of: query, options: .caseInsensitive)
let matches = ranges.map { str[$0] } //
print(matches) // ["play", "play", "play"]

regular expression sample

let query = "play"
let escapedQuery = NSRegularExpression.escapedPattern(for: query)
let pattern = "\\b\(escapedQuery)\\w+" // matches any word that starts with "play" prefix

let ranges = str.ranges(of: pattern, options: .regularExpression)
let matches = ranges.map { str[$0] }

print(matches) // ["playground", "playground", "playground"]

Get string character by index

The method you're looking for is charAt. Here's an example:

String text = "foo";
char charAtZero = text.charAt(0);
System.out.println(charAtZero); // Prints f

For more information, see the Java documentation on String.charAt. If you want another simple tutorial, this one or this one.

If you don't want the result as a char data type, but rather as a string, you would use the Character.toString method:

String text = "foo";
String letter = Character.toString(text.charAt(0));
System.out.println(letter); // Prints f

If you want more information on the Character class and the toString method, I pulled my info from the documentation on Character.toString.

How do I have JavaScript get a substring before a character?

Yes. Try the String.split method: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split

split() returns an array of strings, split by the character you pass to it (in your case, the plus). Just use the first element of the array; it will have everything before the plus:

const string = "foo-bar-baz"
const splittedString = string.split('-')
//splittedString is a 3 element array with the elements 'foo', 'bar', and 'baz'


Related Topics



Leave a reply



Submit