split string and store it in another variable in c# [duplicate] - c#

This question already has answers here:
Split string using backslash
(3 answers)
Closed 5 years ago.
How to Read character after '\':
string PrName = "software\Plan Mobile";

First of all, do not forget #:
string PrName = #"software\Plan Mobile";
Next, if you want just the tail only (i.e. "Plan Mobile") then Substring will do:
// if no '\' found, the entire string will be return
string tail = PrName.Substring(PrName.IndexOf('\\') + 1);
If you want both (all parts), try Split:
// parts[0] == "software"
// parts[1] == "Plan Mobile"
string[] parts = PrName.Split('\\');

Try this:
char charToFind = '\';
string PrName = "software\Plan Mobile";
int indexOfChar = PrName.IndexOf(charToFind);
if (indexOfChar >= 0)
{
string result = PrName.Substring(indexOfChar + 1);
}
Output: result = "Plan Mobile"

I think, you want to split string
string s = "software\Plan Mobile";
// Split string on '\'.
string[] words = s.Split('\');
foreach (string word in words)
{
Console.WriteLine(word);
}
Output:
software
Plan mobile

Related

Read just [Brackets] string from a text file [duplicate]

This question already has answers here:
C# Regex Split - everything inside square brackets
(2 answers)
Closed 4 years ago.
I have a text file named hello.txt with the following text:
[Hello] this is stack overflow and I Love [THIS] a lot. I use [Stack]
for help.
I want just [ ] (brackets string) in a listbox.
I tried:
using (StringReader reader = new StringReader(File Location))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string input = line;
string output = input.Split('[', ']')[1];
MessageBox.Show(output);
}
}
But this doesn't work for me.
This is what you are looking for
string a = "Someone is [here]";
string b = Regex.Match(a, #"\[.*?\]").Groups[0].Value;
Console.WriteLine(b);
//or if you need all occurences
foreach(Match match in Regex.Matches(a, #"\[.*?\]"))
{
Console.WriteLine(match.Groups[0].Value);
}
You can create a function for this which accept three parameter first input string, starting string and ending string and return list of value between those two string
private static IEnumerable<string> GetListOfString(string input, string start, string end)
{
var regex = new Regex(Regex.Escape(start) + "(.*?)" + Regex.Escape(end));
var matches = regex.Matches(input);
return (from object match in matches select match.ToString()).ToList();
}
You can use a regular expression like:
var pattern = #"\[[^\]]*]";
while ((line = reader.ReadLine()) != null) {
var matches = Regex.Matches(line, pattern);
foreach (var m in matches) {
MessageBox.Show(m);
}
}
This pattern looks for anything between square brackets that is not a closing square bracket.
If you want the string between the brackets without the brackets themselves, you can trim the brackets from each match:
MessageBox.Show(m.Value.Substring(1, m.Value.Length - 2));
Or you can use this pattern:
var pattern = #"\[([^\]]*)]";
while ((line = reader.ReadLine()) != null) {
var matches = Regex.Matches(line, pattern);
foreach (Match m in matches) {
MessageBox.Show(m.Groups[1]);
}
}
Here is another way to do that using LINQ
string[] text = "[Hello] this is stack overflow and I Love [THIS] a lot. I use [Stack] for help.".Split(' ');
var wantedString = text.Where(s => s.StartsWith("[") && s.EndsWith("]"));
foreach(string word in wantedString)
{
Console.WriteLine(word);
}

Split string with a comma without spliting inside "" with c# only [duplicate]

This question already has answers here:
split a comma-separated string with both quoted and unquoted strings [duplicate]
(16 answers)
Closed 5 years ago.
How to split a string with a comma and don't split inside - "" with c# only.
For example this string "aa","b,b","asdds","sd,fd,sd,,f"
To this array/list - aa,b,b,asdds,sd,fd,sd,,f
string s = "\"aa\",\"b,b\",\"asdds\",\"sd,fd,sd,,f\""; // The string (\" = ") when write it inside string
List<string> s1 = new List<string>(); // List of the strings without the , and the "
string s2 = ""; // string for adding into the list
bool
first = false, // If arrive to the first "
second = false; // If arrive to the second "
foreach (char c in s) // Move over every char in the string
{
if (second) // If reach the second
{
s1.Add(s2); // Add the string to the list
s2 = ""; // Make s2 ready for new string
first = false; // Make first be ready for another string
second = false; // Make second be ready for another string
}
if (first) // If the string in the quotemark started
{
if (c == '"') // If the string in the quotemark ended
{
second = true; // Reach the second quotemark
}
else // If the string didn't end
{
s2 += c; // Add the char to the string
}
}
if (c == '"' && !first && !second) // If the string just reach the first quotemark in a string
{
first = true; // Reach the first quotemark
}
}
if (second&&first) //For the last string that missed at the end
{
s1.Add(s2); // Add the string to the list
}
string sample = "aa","b,b","asdds","sd,fd,sd,,f";
sample = sample.Replace("\",\", "&");
string[] targetA = sample.Split('&');

Remove all symbols different from numbers and letters in string [duplicate]

This question already has answers here:
c# Regex non letter characters from a string
(2 answers)
Closed 6 years ago.
I need a regex that removes all symbols different from numbers and letters from string. Example:
string address = "TEXT 3 !##$%^&*()_}|{:?> REMOVE ALL SYMBOLS 45";
string result = "TEXT 3 REMOVE ALL SYMBOLS 45";
Any ideas?
try this please
string address = "TEXT 3 !##$%^&*()_}|{\":?> REMOVE ALL SYMBOLS 45";
var sb = new StringBuilder();
foreach (var c in address)
{
if (Char.IsLetterOrDigit(c) || Char.IsWhiteSpace(c))
sb.Append(c);
}
var result = sb.ToString();
It should be faster than regex.
This should work:
var result = new Regex("[^a-zA-Z0-9 ]").Replace(address, string.Empty);
This keeps only whatever in a-Z, A-Z or 0-9 or white space
You can also use linq:
var result2 = new String(address.Where(x => char.IsLetterOrDigit(x)
|| char.IsWhiteSpace(x)).ToArray());
Both worked for me.
My final code:
var addressWithoutEmtySpacesMoreThanOne = Regex.Replace(address, #"\s+", " ");
var result = new Regex("[^a-zA-Zа-яА-Я0-9 -]").Replace(addressWithoutEmtySpaces, "");
customer.Address = result;

Retrieve String Containing Specific substring C#

I am having an output in string format like following :
"ABCDED 0000A1.txt PQRSNT 12345"
I want to retreieve substring(s) having .txt in above string. e.g. For above it should return 0000A1.txt.
Thanks
You can either split the string at whitespace boundaries like it's already been suggested or repeatedly match the same regex like this:
var input = "ABCDED 0000A1.txt PQRSNT 12345 THE.txt FOO";
var match = Regex.Match (input, #"\b([\w\d]+\.txt)\b");
while (match.Success) {
Console.WriteLine ("TEST: {0}", match.Value);
match = match.NextMatch ();
}
Split will work if it the spaces are the seperator. if you use oter seperators you can add as needed
string input = "ABCDED 0000A1.txt PQRSNT 12345";
string filename = input.Split(' ').FirstOrDefault(f => System.IO.Path.HasExtension(f));
filname = "0000A1.txt" and this will work for any extension
You may use c#, regex and pattern, match :)
Here is the code, plug it in try. Please comment.
string test = "afdkljfljalf dkfjd.txt lkjdfjdl";
string ffile = Regex.Match(test, #"\([a-z0-9])+.txt").Groups[1].Value;
Console.WriteLine(ffile);
Reference: regexp
I did something like this:
string subString = "";
char period = '.';
char[] chArString;
int iSubStrIndex = 0;
if (myString != null)
{
chArString = new char[myString.Length];
chArString = myString.ToCharArray();
for (int i = 0; i < myString.Length; i ++)
{
if (chArString[i] == period)
iSubStrIndex = i;
}
substring = myString.Substring(iSubStrIndex);
}
Hope that helps.
First split your string in array using
char[] whitespace = new char[] { ' ', '\t' };
string[] ssizes = myStr.Split(whitespace);
Then find .txt in array...
// Find first element starting with .txt.
//
string value1 = Array.Find(array1,
element => element.Contains(".txt", StringComparison.Ordinal));
Now your value1 will have the "0000A1.txt"
Happy coding.

All elements before last comma in a string in c#

How can i get all elements before comma(,) in a string in c#?
For e.g.
if my string is say
string s = "a,b,c,d";
then I want all the element before d i.e. before the last comma.So my new string shout look like
string new_string = "a,b,c";
I have tried split but with that i can only one particular element at a time.
string new_string = s.Remove(s.LastIndexOf(','));
If you want everything before the last occurrence, use:
int lastIndex = input.LastIndexOf(',');
if (lastIndex == -1)
{
// Handle case with no commas
}
else
{
string beforeLastIndex = input.Substring(0, lastIndex);
...
}
Use the follwoing regex: "(.*),"
Regex rgx = new Regex("(.*),");
string s = "a,b,c,d";
Console.WriteLine(rgx.Match(s).Groups[1].Value);
You can also try:
string s = "a,b,c,d";
string[] strArr = s.Split(',');
Array.Resize(strArr, Math.Max(strArr.Length - 1, 1))
string truncatedS = string.join(",", strArr);

Categories