Split string with string and retrieve value c# - c#

I have below string
string arguments = "-p=C:\Users\mplususer\Documents\SharpDevelop Projects\o9\o9\bin\Debug\o9.exe""-t=False""-r=TestRun";
I want to split string with "-t=" and get false value
if (arguments.Contains("-t="))
{
string[] value = arguments.Split(new string[] { "\"-t=" }, StringSplitOptions.None);
if (value.Length != 0)
{
mode = value[1].Replace("\"", "");
}
}

Simply make an IndexOf:
var i = myString.IndexOf("-t=") + 3;
if(i != -1)
value = myString.SubString(i, myString.IndexOf("\"", i) - i);
You can also use a regex for this:
var r = new Regex("-t (true|false)");
var g = r.Match(myString).Groups;
if(g.Count > 1)
value = Convert.ToBoolean(g[1].ToString());

You can do it also like this like your approach without regex:
string arguments = "-p=C:\\Users\\mplususer\\Documents\\SharpDevelop Projects\\o9\\o9\\bin\\Debug\\o9.exe\" \"-t=False\" \"-r=TestRun";
if (arguments.Contains("-t="))
{
string splitted = arguments.Split(new string[] { "\"-t=" }, StringSplitOptions.None)[1];
string value = splitted.Split(new string[] { "\"" }, StringSplitOptions.None)[0];
}

When you split on "-t", you get two fragments. The fragment after that delimiter also contains a "-r" option - which is the issue you are probably seeing.
If you know that the "-t" option is always followed by a "-r", you could simply split on new string[] { "\"-t=", "\"-r=" }. Then you get three fragments and you still want the second one (at index 1).

Related

List and array comparison

I have a requirement wherein I have a value in Viewbag.Keyword like "Johnson and Jen" so I have to split this value and compare it with List.
I was trying the below code but facing error some or the other way(eg; this is char not string and so on) and it doesn't look like smart coding as per latest functionalities available in framework 4.5
var str = Convert.ToString(ViewBag.Keyword);
string[] str1 = str.Split(' ');
for (int j = 0; j < str1.Length;j++)
{
string str2 = Convert.ToString(str[j]);
if (result.Document.ContactName.IndexOf(str2,
StringComparison.CurrentCultureIgnoreCase) != -1)
Note: "ContactName" is string.
Please help with some latest code which improves performance.
You can use linq to check if result.Document.Name contains a word from array.
var str = Convert.ToString(ViewBag.Keyword);
string[] str1 = str.Split(' ');
var names = str1.Where(x => (result.Document.ContactName.Contains(x))).ToList();
You can compare those names are on that string like below,
Remember comparison is case sensitive
var str = Convert.ToString(ViewBag.Keyword);
string[] str1 = str.Split(' ');
if(str1.Any(result.Document.ContactName.Contains)){
//Do Something
}
Example -
var str = "Johnson and Jen";
string[] str1 = str.Split(' ');
string result = "Jendasdbnoahsdasnd"; // I assume your ContactName result is like this
if (str1.Any(result.Contains)) // This gives true because Jen in the string
{
//Do Something
}
But, for the string result = "jendasdbnoahsdasnd" it gives false because of the case.
If you need to check for the exact match of the words you get by splitting the keyword string using a white space against the contact name property from the collection then you can use a regular expression to do that.
The regular expression is of the form \bTheWordGoesHere\b where \b is the word boundary delimiter
Check this sample code snippet.
var keyword = "Johnson and Jen";
var arr = keyword.Split(' ');
var contactName = "Johnson anderson mobile";
for (var i = 0; i < arr.Length; i++)
{
var pattern = string.Format("\\b{0}\\b", arr[i]);
if (Regex.IsMatch(contactName, pattern, RegexOptions.IgnoreCase))
{
// do something
Console.WriteLine("contactName contains the word \"" + arr[i] + "\"");
}
}
rextester link
Below is a sample code for doing the same using clean code
var str = Convert.ToString(ViewBag.Keyword);
var possibleNames = str.split(' ');
//to check if any match exists
bool anyMatch = possibleNames.Any(n => n.Equals(result.Document.ContactName, StringComparison.InvariantCultureIgnoreCase));
//get matched names
var matchedNames = possibleNames.Where(n => n.Equals(result.Document.ContactName, StringComparison.InvariantCultureIgnoreCase));
//do whatever you want with matchedNames now
var array = matchedNames.ToArray();
var list = matchedNames.ToList();
You can split the string "Johnson and Jen" by using another string i.e. " and " this will exactly give you the names which will be appropriate to check against the contact name.
You can check about the Split function here and here
To check whether a property contains a specified string or not you can use the IndexOf method - a simple sample code snippet is given below, you can run this sample code snippet here.
var keyword = "Johnson and Jen";
var arr = keyword.Split(new string[] { " and " }, StringSplitOptions.None);
var contactName = "Johnson";
for (var i = 0; i < arr.Length; i++)
{
if (contactName.IndexOf(arr[i], StringComparison.OrdinalIgnoreCase) >= 0)
{
// do something
Console.WriteLine("contactName contains the string \"" + arr[i] + "\"");
}
}
The code snippet for your scenario would be as follows and in your code you don't need the unnecessary type casting i.e. string str2 = Convert.ToString(str[j]); because str[j] is already a string
var keyword = Convert.ToString(ViewBag.Keyword);
var arr = name.Split(new string[] { " and " }, StringSplitOptions.None);
for (int i = 0; i < arr.Length; i++)
{
if (result.Document.ContactName.IndexOf(arr[i], StringComparison.OrdinalIgnoreCase) != -1)
{
// do something
}
}
Using the StringComparison parameter with its value as StringComparison.OrdinalIgnoreCase will do a case insensitive search

Get Text From file C#

I am reading text file line By line and in that I want to get data between special characters after checking whether line containing special character or not.In my case I want to check whether line contains <#Tag()> and if it contains then fetch the string between () i.e. line is having <#Tag(param1)> then it should return param1
But the problem is line may contains more then one <#Tag()>
For Example Line is having - <#Tag(value1)> <#Tag(value2)> <#Tag(value3)>
Then it should return first value1 then value2 and then value3
string contents = File.ReadAllText(#"D:\Report Format.txt");
int start = contents.IndexOf("Header") + "Header".Length;
int end = contents.IndexOf("Data") - "Header".Length;
int length = end - start;
string headerData = contents.Substring(start, length);
headerData = headerData.Trim(' ', '-');
MessageBox.Show(headerData);
using (StringReader reader = new StringReader(headerData))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains("<#Tag"))
{
string input = line;
string output = input.Split('<', '>')[1];
MessageBox.Show(output);
Globals.Tags.SystemTagDateTime.Read();
string newoutput = Globals.Tags.SystemTagDateTime.Value.ToString();
input = input.Replace(output, newoutput);
input = Regex.Replace(input, "<", "");
input = Regex.Replace(input, ">", "");
MessageBox.Show(input);
}
}
}
Try following
var matches = Regex.Matches(line, #"(?<=\<\#Tag\()\w+(?=\)\>)")
foreach (Match match in matches)
MessageBox.Show(match.Value);
If you want to accomplish context described in comments try following.
var line = "<#Tag(value1)> <#Tag(value2)> <#Tag(value3)>";
var matches = Regex.Matches(line, #"(?<=\<\#Tag\()\w+(?=\)\>)");
//use matches in your case to find values. i assume 10, 20 , 30
var values = new Dictionary<string, int>() { { "value1", 10 }, { "value2", 20 }, { "value3", 30 } };
const string fullMatchRegexTemplate = #"\<\#Tag\({0}\)\>";
foreach (var value in values)
Regex.Replace(line, string.Format(fullMatchRegexTemplate, value.Key), value.Value.ToString());
This might do the trick for you
[^a-zA-Z0-9]
Basically it matches all non-alphanumeric characters.
private void removeTag()
{
string n = "<#Tag(value1)> <#Tag(value2)> <#Tag(value3)>";
string tmp = Regex.Replace(n, "Tag+", "");
tmp = Regex.Replace(tmp, "[^0-9a-zA-Z]+", ",") ;
}
Another one could be
string tmp = Regex.Replace(n, "[^0-9a-zA-Z]*[Tag]*[^0-9a-zA-Z]", ",");
You could do this with a regex (I'll work on one)- but as a simple shortcut just do:
var tags = line.Split(new string[] { "<#Tag" }, StringSplitOptions.None);
foreach(var tag in tags)
{
//now parse each one
}
I see tchelidze just posted regex that looks pretty good so I'll defer to that answer as the regex one.
You can also collect them after splitting the string by the constant values <#Tag( and )> like this:
string str = "<#Tag(value1)> <#Tag(value2)> <#Tag(value3)>";
string[] values = str.Split(new string[] { "<#Tag(", ")>" }, StringSplitOptions.RemoveEmptyEntries);
values contains:
value1, value2, value3
Show the results in MessageBox:
foreach (string val in values) {
if (!(String.IsNullOrEmpty(val.Trim()))) {
MessageBox.Show(val);
}
}
Edit based on you comment:
Can i display complete value1 value2 value3 in one message box not with comma but with the same spacing as it was
string text = "";
foreach (string val in values) {
text += val;
}
MessageBox.Show(text);
Based on the comment:
Now the last query Before showing it in message box I want to replace it by thier values for example 10 20 and 30
string text = "";
foreach (string val in values) {
// where val is matching your variable (let's assume you are using dictionary for storing the values)
// else is white space or other... just add to text var.
if (yourDictionary.ContainsKey(val)) {
text += yourDictionary[val];
} else {
text += val;
}
}
MessageBox.Show(text);

Parsing a string with, seemingly, no delimiter

I have the following string that I need to parse out so I can insert them into a DB. The delimiter is "`":
`020 Some Description `060 A Different Description `100 And Yet Another `
I split the string into an array using this
var responseArray = response.Split('`');
So then each item in the responseArrray[] looks like this: 020 Some Description
How would I get the two different parts out of that array? The 1st part will be either 3 or 4 characters long. 2nd part will be no more then 35 characters long.
Due to some ridiculous strangeness beyond my control there is random amounts of space between the 1st and 2nd part.
Or put the other two answers together, and get something that's more complete:
string[] response = input.Split(`);
foreach (String str in response) {
int splitIndex = str.IndexOf(' ');
string num = str.Substring(0, splitIndex);
string desc = str.Substring(splitIndex);
desc.Trim();
}
so, basically you use the first space as a delimiter to create 2 strings. Then you trim the second one, since trim only applies to leading and trailing spaces, not everything in between.
Edit: this a straight implementation of Brad M's comment.
You can try this solution:
var inputString = "`020 Some Description `060 A Different Description `100 And Yet Another `";
int firstWordLength = 3;
int secondWordMaxLength = 35;
var result =inputString.Split('`')
.SelectMany(x => new[]
{
new String(x.Take(firstWordLength).ToArray()).Trim(),
new String(x.Skip(firstWordLength).Take(secondWordMaxLength).ToArray()).Trim()
});
Here is the result in LINQPad:
Update: My first solution has some problems because the use of Trim after Take.Here is another approach with an extension method:
public static class Extensions
{
public static IEnumerable<string> GetWords(this string source,int firstWordLengt,int secondWordLenght)
{
List<string> words = new List<string>();
foreach (var word in source.Split(new[] {'`'}, StringSplitOptions.RemoveEmptyEntries))
{
var parts = word.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
words.Add(new string(parts[0].Take(firstWordLengt).ToArray()));
words.Add(new string(string.Join(" ",parts.Skip(1)).Take(secondWordLenght).ToArray()));
}
return words;
}
}
And here is the test result:
Try this
string response = "020 Some Description060 A Different Description 100 And Yet Another";
var responseArray = response.Split('`');
string[] splitArray = {};
string result = "";
foreach (string it in responseArray)
{
splitArray = it.Split(' ');
foreach (string ot in splitArray)
{
if (!string.IsNullOrWhiteSpace(ot))
result += "-" + ot.Trim();
}
}
splitArray = result.Substring(1).Split('-');
string[] entries = input.Split('`');
foreach (string s in entries)
GetStringParts(s);
IEnumerable<String> GetStringParts(String input)
{
foreach (string s in input.Split(' ')
yield return s.Trim();
}
Trim only removes leading/trailing whitespace per MSDN, so spaces in the description won't hurt you.
If the first part is an integer
And you need to account for some empty
For me the first pass was empty
public void parse()
{
string s = #"`020 Some Description `060 A Different Description `100 And Yet Another `";
Int32 first;
String second;
if (s.Contains('`'))
{
foreach (string firstSecond in s.Split('`'))
{
System.Diagnostics.Debug.WriteLine(firstSecond);
if (!string.IsNullOrEmpty(firstSecond))
{
firstSecond.TrimStart();
Int32 firstSpace = firstSecond.IndexOf(' ');
if (firstSpace > 0)
{
System.Diagnostics.Debug.WriteLine("'" + firstSecond.Substring(0, firstSpace) + "'");
if (Int32.TryParse(firstSecond.Substring(0, firstSpace), out first))
{
System.Diagnostics.Debug.WriteLine("'" + firstSecond.Substring(firstSpace-1) + "'");
second = firstSecond.Substring(firstSpace).Trim();
}
}
}
}
}
}
You can get the first part by finding the first space and make a substring. The second is also a Substring. Try something like this.
foreach(string st in response)
{
int index = response.IndexOf(' ');
string firstPart = response.Substring(0, index);
//string secondPart = response.Substring(response.Lenght-35);
//better use this
string secondPart = response.Substring(index);
secondPart.Trim();
}

How to get a word in string C#

Given :
string command = "<CP1><SSA1>";
string command_2 = "<CP1><MPS>";
How can I get the word "CP1" and "1" from 'SSA1' in command and for command_2 is "CP1" and "MPS" then set to another variables?
I already search the similar question but still not found the best answer.
Edited :
For command variable, I want get 'CP1' from CP1 and '1' from SSA1. And for command_2 variable I want get 'CP1' from CP1 and 'MPS' from MPS.
You just need to get strings between angled brackets.. then you just replace "SSA" with "" and you have all the words you wanted !!!
using System.IO;
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
class Program
{
static void Main()
{
string command = "<CP1><SSA1>";
string command_2 = "<CP1><MPS>";
prnt(command);
prnt(command_2);
//prnt(command+command_2); //even this will work :)
}
private static void prnt(string str)
{
List<string> l = ExtractFromString(str,"<",">");
foreach(string ll in l)
Console.WriteLine(ll.Replace("SSA",""));
}
private static List<string> ExtractFromString(string text, string start, string end)
{
List<string> Matched = new List<string>();
int index_start = 0, index_end=0;
bool exit = false;
while(!exit)
{
index_start = text.IndexOf(start);
index_end = text.IndexOf(end);
if (index_start != -1 && index_end != -1)
{
Matched.Add(text.Substring(index_start + start.Length, index_end - index_start - start.Length));
text = text.Substring(index_end + end.Length);
}
else
exit = true;
}
return Matched;
}
}
Output:
CP1
1
CP1
MPS
Source of Extract method: Extract all strings between two strings
You're parsing XML, use XElement classes instead. Then use String or Regex classes to parse tag string content.
this is the code:
string s1 = "<CP1><SSA1>";
int start = s1.IndexOf("<CP");
int end = s1.IndexOf(">"); string
numString = s1.Substring(start + 3, end-start-3); // get the 1
start = s1.IndexOf("<SSA");
end = s1.Length-1;
numString = s1.Substring(start + 4, end - start - 4); // get the 1
with this code you should receive the numbers after your token, it's doesn't matter how much digits it contain.
To convert the string to int use Parse function, like this: int.Parse(numString)
Same answer to the second string
#Chuki2
I dont know what exactly you want to achieve.. but it could be a way to do this.. check it out below..!!
string command = "<CP1><SSA1>";
string command_2 = "<CP1><MPS>";
command = command.Replace("<", "#").Replace(">", "#");
command_2 = command_2.Replace("<", "#").Replace(">", "#");
string[] val = command.Split(
new char[]{'#'},
StringSplitOptions.RemoveEmptyEntries
);
string[] val_2 = command_2.Split(
new char[] { '#' },
StringSplitOptions.RemoveEmptyEntries
);
//now because you want to get the only "1" from "SSA1"
//well i dont know what really you want to do but it could be one way to do this.
string lastParameter = val[val.Length-1];
val[val.Length - 1] = lastParameter.Substring(lastParameter.Length - 1);
Another way:
string[] parts = command.Split(new char[] {'<', '>'},StringSplitOptions.RemoveEmptyEntries);
string part1 = parts[0];
string part2 = parts[1].StartsWith("SSA") : parts[1].Substring(3) : parts[1];

How to make a first letter capital in C#

How can the first letter in a text be set to capital?
Example:
it is a text. = It is a text.
public static string ToUpperFirstLetter(this string source)
{
if (string.IsNullOrEmpty(source))
return string.Empty;
// convert to char array of the string
char[] letters = source.ToCharArray();
// upper case the first char
letters[0] = char.ToUpper(letters[0]);
// return the array made of the new char array
return new string(letters);
}
It'll be something like this:
// precondition: before must not be an empty string
String after = before.Substring(0, 1).ToUpper() + before.Substring(1);
polygenelubricants' answer is fine for most cases, but you potentially need to think about cultural issues. Do you want this capitalized in a culture-invariant way, in the current culture, or a specific culture? It can make a big difference in Turkey, for example. So you may want to consider:
CultureInfo culture = ...;
text = char.ToUpper(text[0], culture) + text.Substring(1);
or if you prefer methods on String:
CultureInfo culture = ...;
text = text.Substring(0, 1).ToUpper(culture) + text.Substring(1);
where culture might be CultureInfo.InvariantCulture, or the current culture etc.
For more on this problem, see the Turkey Test.
If you are using C# then try this code:
Microsoft.VisualBasic.StrConv(sourceString, Microsoft.VisualBasic.vbProperCase)
I use this variant:
private string FirstLetterCapital(string str)
{
return Char.ToUpper(str[0]) + str.Remove(0, 1);
}
If you are sure that str variable is valid (never an empty-string or null), try:
str = Char.ToUpper(str[0]) + str[1..];
Unlike the other solutions that use Substring, this one does not do additional string allocations. This example basically concatenates char with ReadOnlySpan<char>.
I realize this is an old post, but I recently had this problem and solved it with the following method.
private string capSentences(string str)
{
string s = "";
if (str[str.Length - 1] == '.')
str = str.Remove(str.Length - 1, 1);
char[] delim = { '.' };
string[] tokens = str.Split(delim);
for (int i = 0; i < tokens.Length; i++)
{
tokens[i] = tokens[i].Trim();
tokens[i] = char.ToUpper(tokens[i][0]) + tokens[i].Substring(1);
s += tokens[i] + ". ";
}
return s;
}
In the sample below clicking on the button executes this simple code outBox.Text = capSentences(inBox.Text.Trim()); which pulls the text from the upper box and puts it in the lower box after the above method runs on it.
Take the first letter out of the word and then extract it to the other string.
strFirstLetter = strWord.Substring(0, 1).ToUpper();
strFullWord = strFirstLetter + strWord.Substring(1);
text = new String(
new [] { char.ToUpper(text.First()) }
.Concat(text.Skip(1))
.ToArray()
);
this functions makes capital the first letter of all words in a string
public static string FormatSentence(string source)
{
var words = source.Split(' ').Select(t => t.ToCharArray()).ToList();
words.ForEach(t =>
{
for (int i = 0; i < t.Length; i++)
{
t[i] = i.Equals(0) ? char.ToUpper(t[i]) : char.ToLower(t[i]);
}
});
return string.Join(" ", words.Select(t => new string(t)));;
}
string str = "it is a text";
// first use the .Trim() method to get rid of all the unnecessary space at the begining and the end for exemple (" This string ".Trim() is gonna output "This string").
str = str.Trim();
char theFirstLetter = str[0]; // this line is to take the first letter of the string at index 0.
theFirstLetter.ToUpper(); // .ToTupper() methode to uppercase the firstletter.
str = theFirstLetter + str.substring(1); // we add the first letter that we uppercased and add the rest of the string by using the str.substring(1) (str.substring(1) to skip the first letter at index 0 and only print the letters from the index 1 to the last index.)
Console.WriteLine(str); // now it should output "It is a text"
static String UppercaseWords(String BadName)
{
String FullName = "";
if (BadName != null)
{
String[] FullBadName = BadName.Split(' ');
foreach (string Name in FullBadName)
{
String SmallName = "";
if (Name.Length > 1)
{
SmallName = char.ToUpper(Name[0]) + Name.Substring(1).ToLower();
}
else
{
SmallName = Name.ToUpper();
}
FullName = FullName + " " + SmallName;
}
}
FullName = FullName.Trim();
FullName = FullName.TrimEnd();
FullName = FullName.TrimStart();
return FullName;
}
string Input = " it is my text";
Input = Input.TrimStart();
//Create a char array
char[] Letters = Input.ToCharArray();
//Make first letter a capital one
string First = char.ToUpper(Letters[0]).ToString();
//Concatenate
string Output = string.Concat(First,Input.Substring(1));
Try this code snippet:
char nm[] = "this is a test";
if(char.IsLower(nm[0])) nm[0] = char.ToUpper(nm[0]);
//print result: This is a test

Categories

Resources