I have been trying to extract some text in between and after some string.
The text is always different but the string to use by indexOf method is always same
Here is how the string Data looks Like.
4D534D3839373400000000000000000001000000
61705F6B6C6F672E6C737400000000000800E0AF0700F0AF01000000
73756D6D6172792E68746D6C000000000000C0AFFFFFD7AF01000000
703166316532336535652E68746D6C000000C0AFFFFFD7AF01000000
703266316532336535652E68746D6C000000C0AFFFFFD7AF01000000
6472616D2E6C7374000000000000000000000080FFFFFFBF01000000
6F63696D656D2E6C737400000000000000006008FF3F600801000000
72706D5F636F64652E6C73740000000000002000FFFF210001000000
72706D5F646174612E6C73740000000000002900FFFF290001000000
72706D5F6D73672E6C737400000000000800F8AF0750F8AF01000000
646174612E7374617200645BC07B718F11000000E01117
This value is always constant: 01000000
this is how it looks like when extracted:
4D534D38393734000000000000000000
61705F6B6C6F672E6C737400000000000800E0AF0700F0AF
73756D6D6172792E68746D6C000000000000C0AFFFFFD7AF
703166316532336535652E68746D6C000000C0AFFFFFD7AF
703266316532336535652E68746D6C000000C0AFFFFFD7AF
6472616D2E6C7374000000000000000000000080FFFFFFBF
6F63696D656D2E6C737400000000000000006008FF3F6008
72706D5F636F64652E6C73740000000000002000FFFF2100
72706D5F646174612E6C73740000000000002900FFFF2900
72706D5F6D73672E6C737400000000000800F8AF0750F8AF
646174612E7374617200645BC07B718F11000000E01117
And this is what I have tried so far I tried extracting indexes of all: 01000000
using this method:
public static List<int> AllIndexesOf(this string str, string value)
{
if (String.IsNullOrEmpty(value))
throw new ArgumentException("the string to find may not be empty", "value");
List<int> indexes = new List<int>();
for (int index = 0; ; index += value.Length)
{
index = str.IndexOf(value, index);
if (index == -1)
return indexes;
indexes.Add(index);
}
}
How can I loop through all indexes and get the desired data.
Thanks
There's no need to do this manually using IndexOf, you can simply split the string based on the string:
var s = "4D534D3.....";
var results = s.Split(new[] {"01000000"}, StringSplitOptions.RemoveEmptyEntries);
Related
I was just wondering if there is a way of comparing c# strings with a startIndex for the first one. I have a long string and an index and want to find if the next characters are equal to a string. The only way I have found to do this is:
public static bool Equals (string longString, int index, string compare) => longString.Substring(index, compare.Length) == compare;
I think this is inefficient because you are unnecessarily creating a substring for each time you compare a new string at the index. Is there a more efficient way? I looked at string.Equals but it doesn't look like something I would be comfortable trying to rewrite.
string.Compare(longString, startIndex, compare, 0, compare.Length, isIgnoreCase) == 0;
Please see:
https://learn.microsoft.com/en-us/dotnet/api/system.string.compare
This is the best solution I have found.
public static bool Equals (string longString, int index, string compare)
{
if (longString.Length > (index + compare.Length))
return false;
for (int n = 0; n < compare.Length; n++)
{
if (longString[index + n] != compare[n])
return false;
}
return true;
}
IndexOf() contains an overload where we can set startIndex and check whether the string contains desired word, then we should check if the sub-string after the startIndex has the same length as the desired word and note that the following solution doesn't create a new sub-string at all:
var startIndex = 2;
var longString = "56789";
var wordToFind = "789";
var isEqual = longString.IndexOf(wordToFind, startIndex) != -1 && wordToFind.Length == (longString.Length - startIndex);
Console.WriteLine(isEqual);
I have a multiline textbox that contains 10 digit mobile numbers separated by comma. I need to achieve string in group of at least 100 mobile numbers.
100 mobile numbers will be separated by 99 comma in total. What i am trying to code is to split the strings containing commas less than 100
public static IEnumerable<string> SplitByLength(this string str, int maxLength)
{
for (int index = 0; index < str.Length; index += maxLength) {
yield return str.Substring(index, Math.Min(maxLength, str.Length - index));
}
}
By using above code, I can achieve 100 numbers as 100 numbers will have 10*100(for mobile number)+99(for comma) text length. But the problem here is user may enter wrong mobile number like 9 digits or even 11 digits.
Can anyone guide me on how can I achieve this.
Thank you in advance.
You could use this extension method to put them into max-100 number groups:
public static IEnumerable<string[]> SplitByLength(this string str, string[] splitBy, StringSplitOptions options, int maxLength = int.MaxValue)
{
var allTokens = str.Split(splitBy, options);
for (int index = 0; index < allTokens.Length; index += maxLength)
{
int length = Math.Min(maxLength, allTokens.Length - index);
string[] part = new string[length];
Array.Copy(allTokens, index, part, 0, length);
yield return part;
}
}
Sample:
string text = string.Join(",", Enumerable.Range(0, 1111).Select(i => "123456789"));
var phoneNumbersIn100Groups = text.SplitByLength(new[] { "," }, StringSplitOptions.None, 100);
foreach (string[] part in phoneNumbersIn100Groups)
{
Assert.IsTrue(part.Length <= 100);
Console.WriteLine(String.Join("|", part));
}
You have a few options,
Put some kind of mask on the input data to prevent the user entering invalid data. In your UI you could then flag the error and prompt the user to reenter correct information. If you go down this route then something like this string[] nums = numbers.Split(','); will be fine.
Alternatively, you could use regex.split or regex.match and match on the pattern. Something like this should work assuming your numbers are in a string with a leading comma or space
Regex regex = new Regex("(\s|,)\d{10},)";
string[] nums = regex.Split(numbers);
This be can resolved with a simple Linq code
public static IEnumerable<string> SplitByLength(this string input, int groupSize)
{
// First split the input to the comma.
// this will give us an array of all single numbers
string[] numbers = input.Split(',');
// Now loop over this array in groupSize blocks
for (int index = 0; index < numbers.Length; index+=groupSize)
{
// Skip numbers from the starting position and
// take the following groupSize numbers,
// join them in a string comma separated and return
yield return string.Join(",", numbers.Skip(index).Take(groupSize));
}
}
I randomly trying to make this code works. The problem that I have is I can't find the string in some string, because char only takes one character.
Is there another way to do it?
e.g. I can find how many char "e" in "excellent", But I can't find "ll". It'll give me error.
The code which I use:
try
{
int count = label1.Text.Split(Convert.ToChar(textBox1.Text)).Length - 1;
MessageBox.Show(count.ToString());
}
catch
{
messagebox.show("error");
}
Thats why I am using try to catch the error.
This is because you use Convert.ToChar(...) which is supposed to take only convertible string to char (that is, consists of a single character, but "ll" consists of two characters).
You could create an extension for string to do what you want:
public static class StringExtensions {
public static List<int> AllIndexesOf(this string str, string value) {
if (String.IsNullOrEmpty(value))
throw new ArgumentException("the string to find may not be empty", "value");
List<int> indexes = new List<int>();
for (int index = 0; ; index += value.Length) {
index = str.IndexOf(value, index);
if (index == -1)
return indexes;
indexes.Add(index);
}
}
}
And then just use it like:
int count = label1.Text.AllIndexesOf(textBox1.Text).Count;
I have a very big string with a lot of usernames. I want to extract the names from the string. That means I have one big string with lot of names in it. At the end I want every username in a string array.
An example of the string:
blablablabla#User;\u0004User\username,blablablablablablablabla#User;\u0004User\anotherusername,#Viewblablablablablablablabla
Search for: u0004User\
Save all charractes until , is found in the string array
Pseudocode:
string [] array = new string []{};
int i = 0;
foreach (var c in bigdata)
{
if(c == "u0004User\")
{
array[i] = c.AllCharactersUntil(',');
i++;
//AllCharactersUntil is a pseudo function
}
}
You can use string.IndexOf to find the index of "u0004User\" then again to find the following comma. Then use string.Substring to get the name. Keeping track of the current index and using it to tell IndexOf where to start searching from.
string bigdata =
#"blablablabla#User;\u0004User\username,blablablablablablablabla#User;\u0004User\anotherusername,#Viewblablablablablablablabla";
string searchValue = #"u0004User\";
int index = 0;
List<string> names = new List<string>();
while (index < bigdata.Length)
{
index = bigdata.IndexOf(searchValue, index);
if (index == -1) break;
int start = index + searchValue.Length;
int end = bigdata.IndexOf(',', start);
if (end == -1) break;
names.Add(bigdata.Substring(start, end - start));
index = end + 1;
}
Console.WriteLine(string.Join(", ", names));
That will give you the following output
username, anotherusername
NOTE
I've assumed that the "\u0004" values are those 6 characters and not a single unicode character. If it is a unicode character then you need the following change
string searchValue = "\u0004User\\";
Here's a simple result:
string input = "blablablabla#User;\\u0004User\username,blablablablablablablabla#User;\\u0004User\anotherusername,#Viewblablablablablablablabla";
List<string> userNames = new List<string>();
foreach (Match match in Regex.Matches(input, #"(u0004User\\)(.*?),", RegexOptions.IgnoreCase))
{
string currentUserName = match.Groups[2].ToString();
userNames.Add(currentUserName); // Add UserName to List
}
I have a string :
id0:xxxxx:id0-value:xxxxx:id1:xxxxxxxx:id1-value:xxxxx:id3:xxxxxxxx:id3-value:xxx
I just need the value for idX-value from the string into array.
How can I achieve it?
The simple way, the value is in position (4x - 1):
var list = input.Split(':');
var outputs = new List<string>();
for (int index = 0; index < list.Count(); index++)
{
if (index % 4 == 3)
outputs.Add(list.ElementAt(index));
}
Use String.Split()
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
String myString = "id0:xxxxx:id0-value:xxxxx:id1:xxxxxxxx:id1-value:xxxxx:id3:xxxxxxxx:id3-value:xxx";
String[] tokens = myString.Split(new Char[] {':'});
The token array will contain {"id0","xxxxx","id0-value","xxxxx","id1","xxxxxxxx","id1-value","xxxxx","id3","xxxxxxxx","d3-value","xxx"}
The second possibility is to use String.IndexOf() and String.Substring().
http://msdn.microsoft.com/en-us/library/5xkyx09y
http://msdn.microsoft.com/en-us/library/aka44szs
Int start = 0;
ArrayList tokens;
while((start = myString.IndexOf("-value:", start)) > -1) {
ArrayList.Add(myString.Substring(start+6, myString.IndexOf(":", start+7);
start += 6; // Jump past what we just found.
}
Split it using a Regex(a regex which splits : coming after x), then split using colon : and use first index as a Dictionary Key and Second index as Dictionary value.