I have a string and index in that string, and want to get the first position of a substring before that index.
e.g., in string:
"this is a test string that contains other string for testing"
Is there a function that:
Returns 42, given the sub-string "string" and the start position 53; and
Returns 15, given the sub-string "string" and the start position 30?
Like IndexOf() where you can start, lastIndexOf also gives you a place to start from going backwards
var myString = "this is a test string that contains other string for testing";
var lastIndexOf = myString.LastIndexOf("string", 30);
Reports the zero-based index position of the last occurrence of a specified string within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string.
Try something like:
var res = yourString.Substring(0, index).LastIndexOf(stringToMatch);
So you want the last index before a given index...
var myString = "this is a test string that contains other string for testing";
myString = String.SubString(0, 53);
var lastIndexOf = myString.LastIndexOf("string");
You can simply take the substring from 0 to index and on this substring ask for the last index of it
YourString.substring(0,index).LastIndexOf("string");
I know I am late to the party but this is the solution that I am using:
public static int FindIndexBefore(this string text, int startIndex, string searchString)
{
for (int index = startIndex; index >= 0; index--)
{
if (text.Substring(index, searchString.Length) == searchString)
{
return index;
}
}
return -1;
}
I tested it on your example and it gave the expected results.
Related
I have a string which has two tokens that bound a substring that I want to extract, but the substring may contain the tokens themselves, so I want between the 1st occurrence of token A and the last occurrence of token B. I also need to search for the tokens in a case-insensitive search.
Tried to wrap my head around using regex to get this, but can't seem to figure it out. Not sure the best approach here. String.split won't work.
I can't modify the casing of the data between the tokens in the string.
Try this, (I've made it into an extension method)
public static string Between(this string value, string a, string b)
{
int posA = value.IndexOf(a);
int posB = value.LastIndexOf(b);
if (posA == -1) || (posB == -1)
{
return "";
}
int adjustedPosA = posA + a.Length;
return (adjustedPosA >= posB) ? "" : value.Substring(adjustedPosA, posB - adjustedPosA);
}
Usage would be:
var myString = "hereIsAToken_andThisIsWhatIwant_andSomeOtherToken";
var whatINeed = myString.Between("hereIsAToken_", "_andSomeOtherToken");
An easy way to approach this problem is the use of the indexOf function provided by the string class. IndexOf returns the first occurence, lastIndexOf as the name suggests, the last one.
string data;
string token1;
string token2;
int start = data.IndexOf(token1)+token1.Length;
int end = data.LastIndexOf(token2);
string result = data.Substring(start, end-start);
From my personal point of view, regex might be a bit overkill here, just try my example :)
Below is my string array :
string[] arr = {
"region1.mp3,region1-sub.mp3,region1-sub1.mp3,region2-sub.mp3",
"region2.mp3,region2-Sub1.mp3",
"region3.mp3"
};
Below is my value which I am trying to search in above string array and get index:
string searchItem = "region1-sub1.mp3";
This is how I am trying to search but getting -1 (-1 indicates search not found I guess):
int index = Array.FindIndex(arr, t => t == searchItem); // -1
I understand that because my records in string array are comma separated that is why this search is failing.
So any other method which can help me find index without looping and generating new string array?
Expected Output : 0
You want to split every string by comma:
int index = Array.FindIndex(arr, t => t.Split(',').Contains(searchItem));
This works even if the string doesn't contain a comma.
This will you give you your desired output.
int index = Array.FindIndex(arr, t => t.Contains(searchItem));
int index = Array.FindIndex(arr, t => t.Contains(searchItem));
This returns 0.
I am trying to break a string at position 4 and then save as another string. The substring works with simple A-Z letters but can you help me with this.
string messageToSend = "P0011%$1%$6%$1%$1%$Heat And Smoke Detector|1%$1%$7%$1%$1%$Sounder|1%$1%$9%$2%$1%$Input Device Zone 2|";
string myString = messageToSend.Substring(1, messageToSend.Length);
Substring has two signatures:
The one you are currently using is Substring(int startIndex, int length).
Your code example at the top starts at index 1 (the second character), and goes "length of string" characters. The problem is this would go one character past the end of the string.
The easy fix for this situation is
string myString = messageToSend.Substring(1, messageToSend.Length - 1);
Note the -1. This will be the same as the "offset" value you are applying to the start of the string.
However, there is a much easier way to do this, and that's with the second form of the method: Substring(int startIndex).
This only asks for the index to start at, and goes all the way to the end of the string. You don't have to worry how long the string it; it will take care of that for you.
Your example can be filtered down to this:
string myString = messageToSend.Substring(1);
Or, if you wanted to start at the 4th index:
string myString = messageToSend.Substring(4);
There's a length mismatch for the remainder of the string. If you need the entire string after your specific index, just use this overload of Substring:
string messageToSend = "P0011%$1%$6%$1%$1%$Heat And Smoke Detector|1%$1%$7%$1%$1%$Sounder|1%$1%$9%$2%$1%$Input Device Zone 2|";
string myString = messageToSend.Substring(4);
If specifying the length, you'd need to account for the characters you removed from the string.
Index of 4 means 5 characters (indexes 0, 1, 2, 3, and 4)
Length starts counting at one, not zero, so add one more to the number of characters to remove.
Total chars removed during your substring operation: 6
If specifying the length of the string to remove, the code would be:
string messageToSend = "P0011%$1%$6%$1%$1%$Heat And Smoke Detector|1%$1%$7%$1%$1%$Sounder|1%$1%$9%$2%$1%$Input Device Zone 2|";
string myString = messageToSend.Substring(1, messageToSend.Length - 6);
Set string.Length - 1
string messageToSend = "P0011%$1%$6%$1%$1%$Heat And Smoke Detector|1%$1%$7%$1%$1%$Sounder|1%$1%$9%$2%$1%$Input Device Zone 2|";
string myString = messageToSend.Substring(1, messageToSend.Length - 1);
This question already has answers here:
How would you count occurrences of a string (actually a char) within a string?
(34 answers)
Closed 8 years ago.
Is there a method to get the number of replacements using .Replace("a", "A"); ?
Example:
String string_1 = "a a a";
String string_2 = string_1.Replace("a", "A");
In this case, the output should be 3, because a was replaced with A 3 times.
You can get the count using .Split function :
string_1.Split(new string[] { "a" }, StringSplitOptions.None).Length-1;
After splitting the string we will get one item more. Because, .Split function returns a string array that contains the substrings in this string that are delimited by elements of a specified string array. So, the Length property's value will be n+1.
You cannot do this directly with string.Replace, but you could use the string.IndexOf to search for your string until it doesn't find a match
int counter = 0;
int startIndex = -1;
string string_1 = "a a a";
while((startIndex = (string_1.IndexOf("a", startIndex + 1))) != -1)
counter++;
Console.WriteLine(counter);
If this becomes of frequent use then you could plan to create an extension method
public static class StringExtensions
{
public static int CountMatches(this string source, string searchText)
{
if(string.IsNullOrWhiteSpace(source) || string.IsNullOrWhiteSpace(searchText))
return 0;
int counter = 0;
int startIndex = -1;
while((startIndex = (source.IndexOf(searchText, startIndex + 1))) != -1)
counter++;
return counter;
}
}
and call it with
int count = string_1.CountMatches("a");
The advantages of IndexOf are in the fact that you don't need to create an array of strings (Split) or an array of objects (Regex.Matches). It is just a plain vanilla loop involving integers.
You can use the Regex.Matches method to find out what would be replaced. Use the Regex.Escape method to escape the string if it would contain any characters that would be treated specially as a regular expression.
int cnt = Regex.Matches(string_1, Regex.Escape("a")).Count;
I have strings that look like this:
1. abc
2. def
88. ghi
I'd like to be able to get the numbers from the strings and put it into a variable and then get the remainder of the string and put it into another variable. The number is always at the start of the string and there is a period following the number. Is there an easy way that I can parse the one string into a number and a string?
May not be the best way, but, split by the ". " (thank you Kirk)
everything afterwards is a string, and everything before will be a number.
You can call IndexOf and Substring:
int dot = str.IndexOf(".");
int num = int.Parse(str.Remove(dot).Trim());
string rest = str.Substring(dot).Trim();
var input = "1. abc";
var match = Regex.Match(input, #"(?<Number>\d+)\. (?<Text>.*)");
var number = int.Parse(match.Groups["Number"].Value);
var text = match.Groups["Text"].Value;
This should work:
public void Parse(string input)
{
string[] parts = input.Split('.');
int number = int.Parse(parts[0]); // convert the number to int
string str = parts[1].Trim(); // remove extra whitespace around the remaining string
}
The first line will split the string into an array of strings where the first element will be the number and the second will be the remainder of the string.
Then you can convert the number into an integer with int.Parse.
public Tuple<int, string> SplitItem(string item)
{
var parts = item.Split(new[] { '.' });
return Tuple.Create(int.Parse(parts[0]), parts[1].Trim());
}
var tokens = SplitItem("1. abc");
int number = tokens.Item1; // 1
string str = tokens.Item2; // "abc"