All elements before last comma in a string in c# - 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);

Related

Split a String on 2nd last occurrence of comma in C#

I have a string say
var str = "xy,yz,zx,ab,bc,cd";
and I want to split it on the 2nd last occurrence of a comma in C# i.e
a = "xy,yz,zx,ab"
b = "bc,cd"
How can I achieve this result?
Let's find the required comma index with a help of LastIndexOf:
var str = "xy,yz,zx,ab,bc,cd";
// index of the 2nd last occurrence of ','
int index = str.LastIndexOf(',', str.LastIndexOf(',') - 1);
Then use Substring:
string a = str.Substring(0, index);
string b = str.Substring(index + 1);
Let's have a look:
Console.WriteLine(a);
Comsole.WriteLine(b);
Outcome:
xy,yz,zx,ab
bc,cd
Alternative "readable" approach ;)
const string text = "xy,yz,zx,ab,bc,cd";
var words = text.Split(',');
var firstBatch = Math.Max(words.Length - 2, 0);
var first = string.Join(",", words.Take(firstBatch));
var second = string.Join(",", words.Skip(firstBatch));
first.Should().Be("xy,yz,zx,ab"); // Pass OK
second.Should().Be("bc,cd"); // Pass OK
You could handle this via regex replacement:
var str = "xy,yz,zx,ab,bc,cd";
var a = Regex.Replace(str, #",[^,]+,[^,]+$", "");
var b = Regex.Replace(str, #"^.*,([^,]+,[^,]+)$", "$1");
Console.WriteLine(a);
Console.WriteLine(b);
This prints:
xy,yz,zx,ab
bc,cd
It you get Microsoft's System.Interactive extensions from NuGet then you can do this:
string output = String.Join(",", str.Split(',').TakeLast(2));

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.

How to split for only one string without using arrays

I've a string 01-India. I want to split on '-' and get only the code 01. How can I do this. I'm a .net newbie. Split function returns a array. Since I need only one string, how can this be done. Is there a ingenious way to do it using split only. Or do I've to use substring only?
Other possibility is
string xy = "01-India";
string xz = xy.Split('-')[0];
You can search for the first occurence of - and then use the method substring to cut the piece out.
var result = input.Substring(0, input.IndexOf('-'))
string str = "01-India";
string prefix = null;
int pos = str.IndexOf('-');
if (pos != -1)
prefix = str.SubString(0,pos);
var str = "01-India";
var hyphenIndex = str.IndexOf("-");
var start = str.substring(0, hyphenIndex);
or you can use regular expression if it is a more complicated string pattern.
Something like this?
var s = "01-India";
var result = s.SubString(0, s.IndexOf("-"));
Since you don't want to use arrays, you could do an IndexOf('-') and then a substring.
string s = "01-India"
int index = s.IndexOf('-');
string code = s.Substring(0, index);
Or, for added fun, you could use String.Remove.
string s = "01-India"
int index = s.IndexOf('-');
string code = s.Remove(index);
string value = "01-India";
string part1 = value.Split('-')[0];

remove last word in label split by \

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 ))
+ #"\";

Strip prefix and value

if I have the string "freq1" or "freq12" and so on, how can I strip out freq and also the number by itself?
string foo = "freq12";
string fooPart = foo.Substring(4); // "12"
int fooNumber = int.parse(fooPart); // 12
if the "freq" part is not constant, then you can use regular expressions:
using System.Text.RegularExpressions;
string pattern = #"([A-Za-z]+)(\d+)";
string foo = "freq12";
Match match = Regex.Match(foo, pattern);
string fooPart = match.Groups[1].Value;
int fooNumber = int.Parse(match.Groups[2].Value);
Is it always going to be the text freq that prepends the number within the string? If so, your solution is very simple:
var str = "freq12";
var num = int.Parse(str.Substring(4));
Edit: Here's a more generic method in the case that the first part of the string isn't always "freq".
var str = "freq12";
int splitIndex;
for(splitIndex = 0; splitIndex < str.Length; splitIndex++)
{
if (char.IsNumeric(str[splitIndex]))
break;
}
if (splitIndex == str.Length)
throw new InvalidOperationException("The input string does not contain a numeric part.");
var textPart = int.Parse(str.Substring(0, splitIndex));
var numPart = int.Parse(str.Substring(splitIndex));
In the given example, textPart should evaluate to freq and numPart to 12. Let me know if this still isn't what you want.
Try something like this:
String oldString = "freq1";
String newString = oldString.Replace("freq", String.Empty);
If you know that the word "freq" will always be there, then you can do something like:
string number = "freq1".Replace("freq","");
That will result in "1".

Categories