strvalues=#"Emp_Name;Emp_ID;23;24;25;26";
contains values like this
taking the above string as an input the output should be like this
string strresult=#"23;24;25;26";
is there any built in function to do like this
thnaks
prince
Let's add a LINQ solution to the lot...
string result = String.Join(";", values.Split(';').Skip(2).ToArray());
Or another possibility
string result = values.Split(new char[] { ';' }, 3)[2];
Both work, but I wouldn't call them elegant either.
string[] values = strvalues.Split(new char[] { ';' });
values will be a string array containing the first column in values[0], second in values[1], etc.
You can use it like this:
for (int i = 2, i < values.Length, i++) {
Console.WriteLine(values[i]);
}
Regex class?
var strresult = new Regex("([0-9]+;?)*").Match(strvalues).Value;
string strresult = strvalues.Replace("Emp_Name;Emp_ID;", "");
How about...
string result = String.Join(";", strvalues.Split(';'), 2, 4);
Related
This is what I want to convernt: {"apple", "banana"} to "["apple", "banana"]"
I have tried convert string list to string array first, then convert string array to string, but did not work.
var testing = new List<string> {"apple", "banana"};
var arrayTesting = testing.ToArray();
var result = arrayTesting.ToString();
You can use string.Join(String, String[]) method like below to get a , separated string values (like csv format)
var stringifiedResult = string.Join(",", result);
You can try this, should work;
var testing = new List<string> { "apple", "banana" };
var arrayTesting = testing.ToArray<string>();
var result = string.Join(",", arrayTesting);
You can also use StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("\"[");
for (int i = 0; i < arrayTesting.Length; i++)
{
string item = arrayTesting[i];
sb.Append("\"");
sb.Append(item);
if (i == arrayTesting.Length - 1)
{
sb.Append("\"]");
}
else
sb.Append("\",");
}
Console.WriteLine(sb);
Instead of converting it to an array, you could use a linq operator on the list to write all the values into a string.
string temp = "";
testing.ForEach(x => temp += x + ", ");
This will leave you with a single string with each value in the list separated by a comma.
How can I separate www.myurl.com/help,mycustomers into www.myurl.com/help and mycustomers and put them in different string variables?
try this:
string MyString="www.myurl.com/help,mycustomers";
string first=MyString.Split(',')[0];
string second=MyString.Split(',')[1];
If MyString contains multiple parts, you can use:
string[] CS = MyString.Split(',');
And each parts can be accessed like:
CS[0],CS[1],CS[2]
For example:
string MyString="www.myurl.com/help,mycustomers,mysuppliers";
string[] CS = MyString.Split(',');
CS[0];//www.myurl.com/help
CS[1];//mycustomers
CS[2];//mysuppliers
If you want to know more about Split function. Read this.
it can be a comma or a hash
Then you can use String.Split(Char[]) method like;
string s = "www.myurl.com/help,mycustomers";
string first = s.Split(new []{',', '#'},
StringSplitOptions.RemoveEmptyEntries)[0];
string second = s.Split(new [] { ',', '#' },
StringSplitOptions.RemoveEmptyEntries)[1];
As Steve pointed, using indexer might not be good because your string couldn't have any , or #.
You can use for loop also like;
string s = "www.myurl.com/help,mycustomers";
var array = s.Split(new []{',', '#'},
StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(string.Format("{0}: {1}", i, array[i]));
}
You can have a short and sweet solution to this as :
string[] myArray= "www.myurl.com/help,mycustomers".Split(',');
I am having strings like below
<ad nameId="\862094\"></ad>
or comma seprated like below
<ad nameId="\862593\"></ad>,<ad nameId="\862094\"></ad>,<ad nameId="\865599\"></ad>
How to extract nameId value and store in single string like below
string extractedValues ="862094";
or in case of comma seprated string above
string extractedMultipleValues ="862593,862094,865599";
This is what I have started trying with but not sure
string myString = "<ad nameId="\862593\"></ad>,<ad nameId="\862094\"></ad>,<ad
nameId="\865599\"></ad>";
string[] myStringArray = myString .Split(',');
foreach (string str in myStringArray )
{
xd.LoadXml(str);
chkStringVal = xd.SelectSingleNode("/ad/#nameId").Value;
}
Search for:
<ad nameId="\\(\d*)\\"><\/ad>
Replace with:
$1
Note that you must search globally. Example: http://www.regex101.com/r/pL2lX1
Please see code below to extract all numbers in your example:
string value = #"<ad nameId=""\862093\""></ad>,<ad nameId=""\862094\""></ad>,<ad nameId=""\865599\""></ad>";
var matches = Regex.Matches(value, #"(\\\d*\\)", RegexOptions.RightToLeft);
foreach (Group item in matches)
{
string yourMatchNumber = item.Value;
}
Try like this;
string s = #"<ad nameId=""\862094\""></ad>";
if (!(s.Contains(",")))
{
string extractedValues = s.Substring(s.IndexOf("\\") + 1, s.LastIndexOf("\\") - s.IndexOf("\\") - 1);
}
else
{
string[] array = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string extractedMultipleValues = "";
for (int i = 0; i < array.Length; i++)
{
extractedMultipleValues += array[i].Substring(array[i].IndexOf("\\") + 1, array[i].LastIndexOf("\\") - array[i].IndexOf("\\") - 1) + ",";
}
Console.WriteLine(extractedMultipleValues.Substring(0, extractedMultipleValues.Length -1));
}
mhasan, here goes an example of what you need(well almost)
EDITED: complete code (it's a little tricky)
(Sorry for the image but i have some troubles with tags in the editor, i can send the code by email if you want :) )
A little explanation about the code, it replaces all ocurrences of parsePattern in the given string, so if the given string has multiple tags separated by "," the final result will be the numbers separated by "," stored in parse variable....
Hope it helps
I have a string array. It is dynamic and can be of any length(0 also). How can I make a single string from the array, delimited by any separator like ; or | ??
string str = string.empty;
string[] arrOptions = strOptions.Split(new string[]{"\n"}, StringSplitOptions.RemoveEmptyEntries);
Now, have to make the string from arrOptions and put it in str
Use string.Join:
string result = string.Join("\n", arrOptions);
Or simply concat them, if you don't need the separator anymore:
string result = string.Concat(arrOptions);
Use String.Join(separator, objects) method.
You can try both way:
string[] strArr = { "Abc", "DEF", "GHI" };
// int i = 0;
// string final=string.Empty;
//IterationStart:
// if (i < strArr.Length)
// {
// final += strArr[i] + ",";
// i++;
// goto IterationStart;
// }
//Console.WriteLine(final);
string str = string.Join(",", strArr);
Console.WriteLine(str);
str = string.Join( ';', arrOptions );
Try : string.Join(seperator, arrOptions);
You might be looking for the below solution.
string str = string.empty;
string[] arrOptions = strOptions.Split(new string[]{"\n"}, StringSplitOptions.RemoveEmptyEntries);
str = string.Concat(arrOptions);
Thanks,
Praveen
Ok i have a string where i want to remove the last word split by \
for example:
string name ="kak\kdk\dd\ddew\cxz\"
now i want to remove the last word so that i get a new value for name as
name= "kak\kdk\dd\ddew\"
is there an easy way to do this
thanks
How do you get this string in the first place? I assume you know that '' is the escape character in C#. However, you should get far by using
name = name.TrimEnd('\\').Remove(name.LastIndexOf('\\') + 1);
string result = string.Join("\\",
"kak\\kdk\\dd\\ddew\\cxz\\"
.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)
.Reverse()
.Skip(1)
.Reverse()
.ToArray()) + "\\";
Here's a non-regex manner of doing it.
string newstring = name.SubString(0, name.SubString(0, name.length - 1).LastIndexOf('\\'));
This regex replacement should do the trick:
name = Regex.Replace(name, #"\\[a-z]*\\$", "\\");
Try this:
const string separator = "\\";
string name = #"kak\kdk\dd\ddew\cxz\";
string[] names = name.Split(separator.ToCharArray(),
StringSplitOptions.RemoveEmptyEntries);
string result = String.Join(separator, names, 0, names.Length - 1) + separator;
EDIT:I just noticed that name.Substring(0,x) is equivalent to name.Remove(x), so I've changed my answer to reflect that.
In a single line:
name = name = name.Remove(name.Remove(name.Length - 1).LastIndexOf('\\') + 1);
If you want to understand it, here's how it might be written out (overly) verbosely:
string nameWithoutLastSlash = name.Remove(name.Length - 1);
int positionOfNewLastSlash = nameWithoutLastSlash.LastIndexOf('\\') + 1;
string desiredSubstringOfName = name.Remove(positionOfNewLastSlash);
name = desiredSubstringOfName;
My Solution
public static string RemoveLastWords(this string input, int numberOfLastWordsToBeRemoved, char delimitter)
{
string[] words = input.Split(new[] { delimitter });
words = words.Reverse().ToArray();
words = words.Skip(numberOfLastWordsToBeRemoved).ToArray();
words = words.Reverse().ToArray();
string output = String.Join(delimitter.ToString(), words);
return output;
}
Function call
RemoveLastWords("kak\kdk\dd\ddew\cxz\", 1, '\')
string name ="kak\kdk\dd\ddew\cxz\"
string newstr = name.TrimEnd(#"\")
if you working with paths:
string name = #"kak\kdk\dd\ddew\cxz\";
Path.GetDirectoryName(name.TrimEnd('\\'));
//ouput: kak\kdk\dd\ddew
string[] temp = name.Split('\\');
string last = "\\" + temp.Last();
string target = name.Replace(last, "");
For Linq-lovers: With later C# versions you can use SkipLast together with Split and string.Join:
var input = #"kak\kdk\dd\ddew\cxz\";
string result = string.Join( #"\", input
.Split( #"\", StringSplitOptions.RemoveEmptyEntries )
.SkipLast( 1 ))
+ #"\";