C# Reading particular values in a string - c#

I have the following line from a string:
colors numResults="100" totalResults="6806926"
I want to extract the value 6806926 from the above string
How is it possible?
So far, I have used StringReader to read the entire string line by line.
Then what should I do?

I'm sure there's also a regex, but this string approach should work also:
string xmlLine = "[<colors numResults=\"100\" totalResults=\"6806926\">]";
string pattern = "totalResults=\"";
int startIndex = xmlLine.IndexOf(pattern);
if(startIndex >= 0)
{
startIndex += pattern.Length;
int endIndex = xmlLine.IndexOf("\"", startIndex);
if(endIndex >= 0)
{
string token = xmlLine.Substring(startIndex,endIndex - startIndex);
// if you want to calculate with it
int totalResults = int.Parse( token );
}
}
Demo

Consider the this is in Mytext of string type variable
now
Mytext.Substring(Mytext.indexof("totalResults="),7);
//the function indexof will return the point wheres the value start,
//and 7 is a length of charactors that you want to extract
I am using similar of this ........

You can read with Linq2Xml, numResults and totalResults are Attributes, and <colors numResults="100" totalResults="6806926"> is Element, so you can simply get it by nmyXmlElement.Attributes("totalResults").

This function will split the string into a list of key value pairs which you can then pull out whatever you require
static List<KeyValuePair<string, string>> getItems(string s)
{
var retVal = new List<KeyValuePair<String, string>>();
var items = s.Split(' ');
foreach (var item in items.Where(x => x.Contains("=")))
{
retVal.Add(new KeyValuePair<string, string>( item.Split('=')[0], item.Split('=')[1].Replace("\"", "") ));
}
return retVal;
}

You can use regular expressions:
string input = "colors numResults=\"100\" totalResults=\"6806926\"";
string pattern = "totalResults=\"(?<results>\\d+?)\"";
Match result = new Regex(pattern).Match(input);
Console.WriteLine(result.Groups["results"]);
Be sure to have this included:
using System.Text.RegularExpressions;

Related

How to output unique symbols except case c# without LINQ

Output unique symbols ignoring case
IDictionary<char, int> charDict = new Dictionary<char, int>();
foreach (var ch in text)
{
if (!charDict.TryGetValue(ch, out n)) {
charDict.Add(new KeyValuePair<char, int>(ch, 1));
} else
{
charDict[ch]++;
}
}
Appellodppsafs => Apelodsf
And Is it possible not to use LINQ?
Use a HashSet<char> to remember existing characters (that's what Distinct() does internally)
Assuming your input and expected result are type string
string input = "Appellodppsafs";
HashSet<char> crs = new HashSet<char>();
string result = string.Concat(input.Where(x => crs.Add(char.ToLower(x)))); //Apelodsf
You can try this (if you do not have long strings or performance issues):
string str = "Appellodppsafs";
string result = string.Concat(str.Select(s => $"{s}")
.Distinct(StringComparer.InvariantCultureIgnoreCase));
Console.WriteLine(result);
Output:
Apelodsf

I want substring from set of string after a pattern exist in c#

I have 3 string ---
m60_CLDdet2_LOSS2CLF_060520469434_R0RKE_52_GU
m60_CLDdet2_LOSS2CLF_060520469434_R10KE_52_TCRER
m60_CLDdet2_LOSS2CLF_060520469434_R0HKE_52_NT
and I want R0RKE_52_GU, R10KE_52_TCRER,R0HKE_52_NT.
Note: m60_CLDdet2_LOSS2CLF_060520469434 is varying so I want to find substring if R0RKE or R10KE or R0HKE exists
I would suggest using a Regular expression for this, it is much more versatile for pattern matching.
var matches = System.Text.RegularExpressions.Regex.Matches(text, #"(R0RKE|R10KE|R0HKE).*");
I want to find substring if R0RKE or R10KE or R0HKE exists
This LINQ query returns the desired result:
var strings=new[]{"m60_CLDdet2_LOSS2CLF_060520469434_R0RKE_52_GU","m60_CLDdet2_LOSS2CLF_060520469434_R10KE_52_TCRER","m60_CLDdet2_LOSS2CLF_060520469434_R0HKE_52_NT"};
string[] starts = { "R0RKE", "R10KE", "R0HKE" };
var result = strings
.Select(str => new { str, match = starts.FirstOrDefault(s => str.IndexOf("_" + s) >= 0)})
.Where(x => x.match != null)
.Select(x => x.str.Substring(x.str.IndexOf(x.match)));
Console.Write(String.Join(",", result)); // R0RKE_52_GU,R10KE_52_TCRER,R0HKE_52_NT
I write it into static method:
private static string TakeIt(string inputString)
{
if (!Regex.IsMatch(inputString, "(R0RKE|R10KE|R0HKE)"))
{
return string.Empty;
}
var regex = new Regex(#"_");
var occurances = regex.Matches(inputString);
var index = occurances[3].Index + 1;
return inputString.Substring(index, inputString.Length - index);
}
void Main()
{
var string1 = "m60_CLDdet2_LOSS2CLF_060520469434_R0RKE_52_GU";
var string2 = "m60_CLDdet2_LOSS2CLF_060520469434_R10KE_52_TCRER";
var string3 = "m60_CLDdet2_LOSS2CLF_060520469434_R0HKE_52_NT";
var string4 = "m60_CLDdet2_LOSS2CLF_060520469434_hhhhh";
Console.WriteLine(TakeIt(string1));
Console.WriteLine(TakeIt(string2));
Console.WriteLine(TakeIt(string3));
Console.WriteLine(TakeIt(string4));
}
Hope this help.
Update: added .Any - it simplifies the code and it's just as same efficient.
If you just need to check for three strings inside string array you can do :
static string[] GetStrings(string[] dirty, string[] lookUpValues)
{
List<string> result = new List<string>();
for (int i = 0; i < dirty.Length; i++) if (lookUpValues.Any(dirty[i].Contains)) result.Add(dirty[i]);
return result.ToArray();
}
Usage: string[] result = GetStrings(dirty, new[] {"R0RKE", "R10KE", "R0HKE"});
Also you can use LINQ query and Regex.Matches as others advised.

How to get string after specific string?

How to get string after text "playlist:" ?
var YT= "tag:youtube.com,2008:user:hollywoodlife09:playlist:PLDovhwKa3P88MwGzYxMDMfiAiiEWxAJYj" ;
What I did :
string[] s = YT.Split(':');
But it will give me array i.e s[0],s[1] ... and I am searching for something which can give result after specific text.
I want string after "playlist:", I know it may be easy with Regex,but currently I don't have any idea for Regex..
You can use Substring method
var output = inputString.SubString(inputString.LastIndexOf("playlist") + 8);
Or in this case it can be done using Last method via Split:
string output = YT.Split(':').Last();
Using regex replace, remove everything before the :playlist: with empty string.
string playlist = Regex.Replace(YT, ".*:playlist:", "");
more reusably,
static IEnumerable<KeyValuePair<string, string>> SplitPairs(
this string source,
params char[] seperators)
{
var values = source.Split(seperators);
for(var i = 0; i < values.Length; i += 2)
{
yield return new KeyValuePair<string, string>(
values[i],
values[i + 1]);
}
}
so you could do,
var yTlookup = YT.SplitPairs(':').ToDictionary(p => p.Key, p => p.Value);
var playList = yTLookup["playlist"];
or if you don't want an extension,
var segments = YS.Split(new[] { ':' });
var ySlookup = Enumerable.Range(0, segemnts.Length / 2)
.ToDictionary(i => segments[i * 2], i => segments[(i * 2) + 1]);
so you can do,
var playlist = ysLookup["playlist"];
either approach pays off as soon as you want another value from the sequence.
The regex is .+playlist:([^:])

Pattern based string parse

When I need to stringify some values by joining them with commas, I do, for example:
string.Format("{0},{1},{3}", item.Id, item.Name, item.Count);
And have, for example, "12,Apple,20".
Then I want to do opposite operation, get values from given string. Something like:
parseFromString(str, out item.Id, out item.Name, out item.Count);
I know, it is possible in C. But I don't know such function in C#.
Yes, this is easy enough. You just use the String.Split method to split the string on every comma.
For example:
string myString = "12,Apple,20";
string[] subStrings = myString.Split(',');
foreach (string str in subStrings)
{
Console.WriteLine(str);
}
Possible implementations would use String.Split or Regex.Match
example.
public void parseFromString(string input, out int id, out string name, out int count)
{
var split = input.Split(',');
if(split.length == 3) // perhaps more validation here
{
id = int.Parse(split[0]);
name = split[1];
count = int.Parse(split[2]);
}
}
or
public void parseFromString(string input, out int id, out string name, out int count)
{
var r = new Regex(#"(\d+),(\w+),(\d+)", RegexOptions.IgnoreCase);
var match = r.Match(input);
if(match.Success)
{
id = int.Parse(match.Groups[1].Value);
name = match.Groups[2].Value;
count = int.Parse(match.Groups[3].Value);
}
}
Edit: Finally, SO has a bunch of thread on scanf implementation in C#
Looking for C# equivalent of scanf
how do I do sscanf in c#
If you can assume the strings format, especially that item.Name does not contain a ,
void parseFromString(string str, out int id, out string name, out int count)
{
string[] parts = str.split(',');
id = int.Parse(parts[0]);
name = parts[1];
count = int.Parse(parts[2]);
}
This will simply do what you want but I would suggest you add some error checking. Better still consider serializing/deserializing to XML or JSON.
Use Split function
var result = "12,Apple,20".Split(',');

How to delete last character in a string in C#?

Building a string for post request in the following way,
var itemsToAdd = sl.SelProds.ToList();
if (sl.SelProds.Count() != 0)
{
foreach (var item in itemsToAdd)
{
paramstr = paramstr + string.Format("productID={0}&", item.prodID.ToString());
}
}
after I get resulting paramstr, I need to delete last character & in it
How to delete last character in a string using C#?
Personally I would go with Rob's suggestion, but if you want to remove one (or more) specific trailing character(s) you can use TrimEnd. E.g.
paramstr = paramstr.TrimEnd('&');
build it with string.Join instead:
var parameters = sl.SelProds.Select(x=>"productID="+x.prodID).ToArray();
paramstr = string.Join("&", parameters);
string.Join takes a seperator ("&") and and array of strings (parameters), and inserts the seperator between each element of the array.
string source;
// source gets initialized
string dest;
if (source.Length > 0)
{
dest = source.Substring(0, source.Length - 1);
}
Try this:
paramstr.Remove((paramstr.Length-1),1);
I would just not add it in the first place:
var sb = new StringBuilder();
bool first = true;
foreach (var foo in items) {
if (first)
first = false;
else
sb.Append('&');
// for example:
var escapedValue = System.Web.HttpUtility.UrlEncode(foo);
sb.Append(key).Append('=').Append(escapedValue);
}
var s = sb.ToString();
string str="This is test string.";
str=str.Remove(str.Length-1);
It's better if you use string.Join.
class Product
{
public int ProductID { get; set; }
}
static void Main(string[] args)
{
List<Product> products = new List<Product>()
{
new Product { ProductID = 1 },
new Product { ProductID = 2 },
new Product { ProductID = 3 }
};
string theURL = string.Join("&", products.Select(p => string.Format("productID={0}", p.ProductID)));
Console.WriteLine(theURL);
}
It's good practice to use a StringBuilder when concatenating a lot of strings and you can then use the Remove method to get rid of the final character.
StringBuilder paramBuilder = new StringBuilder();
foreach (var item in itemsToAdd)
{
paramBuilder.AppendFormat(("productID={0}&", item.prodID.ToString());
}
if (paramBuilder.Length > 1)
paramBuilder.Remove(paramBuilder.Length-1, 1);
string s = paramBuilder.ToString();
paramstr.Remove((paramstr.Length-1),1);
This does work to remove a single character from the end of a string. But if I use it to remove, say, 4 characters, this doesn't work:
paramstr.Remove((paramstr.Length-4),1);
As an alternative, I have used this approach instead:
DateFrom = DateFrom.Substring(0, DateFrom.Length-4);
Add a StringBuilder extension method.
public static StringBuilder RemoveLast(this StringBuilder sb, string value)
{
if(sb.Length < 1) return sb;
sb.Remove(sb.ToString().LastIndexOf(value), value.Length);
return sb;
}
then use:
yourStringBuilder.RemoveLast(",");

Categories