Get Substring - everything before certain char
.Net Fiddle example
class Program
{
static void Main(string[] args)
{
Console.WriteLine("223232-1.jpg".GetUntilOrEmpty());
Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
Console.WriteLine("34443553-5.jpg".GetUntilOrEmpty());
Console.ReadKey();
}
}
static class Helper
{
public static string GetUntilOrEmpty(this string text, string stopAt = "-")
{
if (!String.IsNullOrWhiteSpace(text))
{
int charLocation = text.IndexOf(stopAt, StringComparison.Ordinal);
if (charLocation > 0)
{
return text.Substring(0, charLocation);
}
}
return String.Empty;
}
}
Results:
223232
443
34443553
344
34
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
.
Get the string up to a specific character
Expanding on @appzYourLife answer, the following will also trim off the whitespace characters after removing everything after the @ symbol.
import Foundation
var str = "hello, how are you @tom"
if str.contains("@") {
let endIndex = str.range(of: "@")!.lowerBound
str = str.substring(to: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
}
print(str) // Output - "hello, how are you"
UPDATE:
In response to finding the last occurance of the @
symbol in the string and removing it, here is how I would approach it:
var str = "hello, how are you @tom @tim?"
if str.contains("@") {
//Reverse the string
var reversedStr = String(str.characters.reversed())
//Find the first (last) occurance of @
let endIndex = reversedStr.range(of: "@")!.upperBound
//Get the string up to and after the @ symbol
let newStr = reversedStr.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
//Store the new string over the original
str = String(newStr.characters.reversed())
//str = "hello, how are you @tom"
}
Or looking at @appzYourLife answer use range(of:options:range:locale:)
instead of literally reversing the characters
var str = "hello, how are you @tom @tim?"
if str.contains("@") {
//Find the last occurrence of @
let endIndex = str.range(of: "@", options: .backwards, range: nil, locale: nil)!.lowerBound
//Get the string up to and after the @ symbol
let newStr = str.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
//Store the new string over the original
str = newStr
//str = "hello, how are you @tom"
}
As an added bonus, here is how I would approach removing every @
starting with the last and working forward:
var str = "hello, how are you @tom and @tim?"
if str.contains("@") {
while str.contains("@") {
//Reverse the string
var reversedStr = String(str.characters.reversed())
//Find the first (last) occurance of @
let endIndex = reversedStr.range(of: "@")!.upperBound
//Get the string up to and after the @ symbol
let newStr = reversedStr.substring(from: endIndex).trimmingCharacters(in: .whitespacesAndNewlines)
//Store the new string over the original
str = String(newStr.characters.reversed())
}
//after while loop, str = "hello, how are you"
}
Get the beginning of a string until a given char
What about using strtok
and "["
as a delimiter?
#include <string.h> /* for strtok */
#include <stdio.h> /* for printf */
int main()
{
char str[] = "M1[r2][r3]"; // str will be modified by strtok
const char deli[] = "["; // deli could also be declared as [2] or as const char *. Take your pick...
char *token;
token = strtok(str, deli); // can also call strtok(str, "["); and not use variable deli at all
printf("%s", token); // printf("%s", str); will print the same result
/* OUTPUT: M1 */
return 0;
}
How would I get everything before a : in a string Python
Just use the split
function. It returns a list, so you can keep the first element:
>>> s1.split(':')
['Username', ' How are you today?']
>>> s1.split(':')[0]
'Username'
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));
Select all characters in a string until a specific character Ruby
You can avoid creating an unnecessary Array (like Array#split
) or using a Regex (like Array#gsub
) by using.
a = "2.452811139617034,42.10874821716908|3.132087902867818,42.028314077306646|-0.07934861041448178,41.647538468746916|-0.07948265046522918,41.64754863599606"
a[0,a.index('|')]
#=>"2.452811139617034,42.1087482171"
This means select characters at positions 0 up to the index of the first pipe (|
). Technically speaking it is start at position 0 and select the length of n where n is the index of the pipe character which works in this case because ruby uses 0 based indexing.
As @CarySwoveland astutely pointed out the string may not contain a pipe in which case my solution would need to change to
#to return entire string
a[0,a.index('|') || a.size]
# or
b = a.index(?|) ? a[0,b] : a
# or to return empty string
a[0,a.index('|').to_i]
# or to return nil
a[0,a.index(?|) || -1]
How to get a string after specific character and before specific character in MySQL?
Using the base string function SUBSTRING_INDEX
we can try:
SELECT
SUBSTRING_INDEX(
SUBSTRING_INDEX('lipnice sivá <(Poa glauca)>', '<(', -1), ')>', 1);
If you are using MySQL 8+, then we can REGEXP_REPLACE
for a regex based solution:
SELECT
REGEXP_REPLACE('lipnice sivá <(Poa glauca)>', '^.*<\\((.*?)\\)>.*$', '$1');
Follow the demo link below to see both queries.
Demo
How to get specific character in a string?
You really should clarify the issue you're having; feel free to read How to Ask.
Basic Loop
As far as your question states (from my understanding), you would like to repeatidly call a method and have that method return the index of a string that corresponds to the current call. I would look into the for loop and string.Substring(int), you could also just access the string as a char array (which I do below).
static void Main() {
string myString = "SomeStringData";
for (int i = 0; i < myString.Length; i++)
Console.Write(GetCharacter(myString, i));
}
static char GetCharacter(string data, int index) => data[index];
The code above can be modified to make sequential calls until you need to stop looping which will meet your condition of the first index being returned once the end of the string has been reached:
string myString = "abc";
for (int i = 0; i < myString.Length; i++) {
Console.Write(GetCharacter(myString, i);
// This will reset the loop to make sequential calls.
if (i == myString.Length)
i = 0;
}
If you wish to escape the loop above, you'll need to add some conditional logic to determine if the loop should be broken, or instead of looping, just make individual calls to the GetCharacter(string, int)
method supplied. Also, you should only modify the iteration variable i
if you truly need to; in this case you could switch to a while loop which would be more appropriate:
string myString = "abc";
string response = string.Empty;
int index = 0;
while (response.TrimEnd().ToUpper() != "END") {
Console.WriteLine(GetCharacter(myString, index++));
Console.WriteLine("If you wish to end the test please enter 'END'.");
response = Console.ReadLine();
if (index > myString.Length)
index = 0;
}
Get Character (Expression Body vs Full Body)
C# 6 introduced the ability to write methods as expressions; a method written as an expression is called an Expression-Bodied-Member. For example, the two methods below function in the exact same manner:
static char GetCharacter(string data, int index) => data[index];
static char GetCharacter(string data, int index) {
return data[index];
}
Expression body definitions let you provide a member's implementation in a very concise, readable form. You can use an expression body definition whenever the logic for any supported member, such as a method or property, consists of a single expression.
Related Topics
How to Avoid Duplicate Key Error in Swift When Iterating Over a Dictionary
How to Add a Left Bar Button Without Overriding the Natural Back Button
How to Check If a Type Is Optional in Swift
Cast Any to Float Always Fails in Swift4.1
How to Convert Dispatchtimeinterval to Nstimeinterval (Or Double)
How to Convert a Unsafemutablepointer<Void> to Uint8
Why Is Casting a Struct to Anyobject Not a Compile Error in Swift
Create Endless Cgpath Without Framedrops
Does Swift Have Short-Circuiting Higher-Order Functions Like Any or All
Cannot Call Value of Non-Function Type 'Nshttpurlresponse' Alamofire Objectmapper
Firebase Storage Overwriting Files
Swiftui [Bug] Navigationview and List Not Showing on iPad Simulator Only
Self' Is Only Available in a Protocol or as the Result of a Class Method
Comparing Non-Optional Any to Nil Is Always False