Strip prefix and value - c#

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".

Related

how To get specific part of a string in c#

I have a string
string a = "(something is there),xyz,(something there)";
and, I use this
string s = "(something is there),xyz,(something there)";
int start = s.IndexOf("(") + 1;
int end = s.IndexOf(")", start);
string result = s.Substring(start, end - start);
but I want to use the second part (something there)
how can I do it?
a.Split("(),".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
This will return an array with 3 strings: something is there, xyz, and something there
Not sure what exactly you're doing around this, however this does it in this specific case:
var last = s.Split(',').Last(); // "(something there)"
Or more verbosely for explanation:
var s = "(something is there),xyz,(something there)";
var split = s.Split(','); // [ "(something is there)", "xyz", "(something there)" ]
var last = split.Last(); // "(something there)"
And if you don't want the brackets(en-GB)
var content = last.Trim('(', ')'); // "something there"
If "last" is the same as "second" in this case you can use String.LastIndexOf:
string lastPart = null;
int lastStartIndex = a.LastIndexOf('(');
if (lastStartIndex >= 0)
{
int lastEndIndex = a.LastIndexOf(')');
if (lastEndIndex >= 0)
lastPart = a.Substring(++lastStartIndex, lastEndIndex - lastStartIndex);
}
Here is a solution which extracts all tokens from the string into a List<string>:
int startIndex = -1, endIndex = -1;
var tokens = new List<string>();
while (true)
{
startIndex = a.IndexOf('(', ++endIndex);
if (startIndex == -1) break;
endIndex = a.IndexOf(')', ++startIndex);
if (endIndex == -1) break;
tokens.Add(a.Substring(startIndex, endIndex - startIndex));
}
So now you could use the indexer or Enumerable.ElementAtOrDefault:
string first = tokens[0];
string second = tokens.ElementAtOrDefault(1);
If the list is too small you get null as result. If you just want the last use tokens.Last().
You can use this:
string s = "(something is there),xyz,(something there)";
var start = s.Split(',')[2];
Also You can use:
string s = "(something is there),xyz,(something there)";
Regex regex = new Regex(#"\([^()]*\)(?=[^()]*$)");
Match match = regex.Match("(something is there),xyz,(something there)");
var result = match.Value;
You could use the following if you just want the text:
var s = "(something is there),xyz,(something there)";
var splits = s.Split('(');
var text = splits[2].Trim(')');
If you want to get the text between second '(' and ')' then use the second parameter of IndexOf which sets the starting index for searching
start = s.IndexOf("(", end) + 1;
end = s.IndexOf(")", start);
string secondResult = s.Substring(start, end - start);
If you want to get the string after the last ) use this code:
string otherPart = s.Substring(end+1);

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);

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];

String replace for personalize code generator

I must do a automatic codes generator with user-configurable string with predefined keys and can not find a good way to do it.
For example, a string
OT-{CustomCode}-{Date}-{##}
could generate codes
OT-C0001-20100420-01
OT-C0001-20100420-02
I thought of using RegExpr.Replace(), but I would have problems if the code of a customer was {##}
Any help is welcome! (and sorry for my english)
You can use string.Format():
string generated = string.Format("OT-{0}-{1}-{2}", code, date, num);
The {x} are placeholders for strings to be replaced.
Do you mean an auto-generated code definition is for example:
Foo {##} , Bar {Date}
and that will produce:
Foo 01 , Bar 20100420
Foo 02 , Bar 20100420
don't you ?
I think RegExpr.Replace() is a good solution, to the ## problem you can do something like this:
private void Generate()
{
Regex doubleSharpRegEx = new Regex("{#+}");
string customString = "Foo {####}";
string[] generatedCodes = new string[3];
for (int i = 0; i < generatedCodes.Length; i++)
{
string newString = doubleSharpRegEx.Replace(customString,
match =>
{
// Calculate zero padding for format
// remove brackets
string zeroPadding = match.Value.Substring(1, match.Value.Length - 2);
// replace # with zero
zeroPadding = zeroPadding.Replace('#', '0');
return string.Format("{0:" + zeroPadding + "}", i);
});
generatedCodes[i] = newString;
}
}
And the array generatedCodes contains:
Foo 0000
Foo 0001
Foo 0002
Foo 0003
EDIT:
Lambdas expression work only for framework 3.5.
If you need a solution for 2.0, you must only replace the lambda expression part with a delegate (obviously setting i available for the delegated method e.g. class member)
EDIT 2:
You can combine the 2 answer for example in the following code:
private void Generate2()
{
Regex customCodeRegex = new Regex("{CustomCode}");
Regex dateRegex = new Regex("{Date}");
Regex doubleSharpRegex = new Regex("{#+}");
string customString = "Foo-{##}-{Date}-{CustomCode}-{####}";
string newString = customCodeRegex.Replace(customString, "{0}");
newString = dateRegex.Replace(newString, "{1}");
newString = doubleSharpRegex.Replace(newString,
match =>
{
string zeroPadding = match.Value.Substring(1, match.Value.Length - 2);
zeroPadding = zeroPadding.Replace('#', '0');
return "{2:" + zeroPadding + "}";
});
string customCode = "C001";
string date = DateTime.Today.ToString("yyyyMMdd");
string[] generatedCodes = new string[3];
for (int i = 0; i < generatedCodes.Length; i++)
{
generatedCodes[i] = string.Format(newString, customCode, date, i);
}
}
The StringBuilder class provides an efficient replace:
string code = "C0001";
DateTime date = DateTime.Now;
int count = 1;
String formatString = "OT-{CustomCode}-{Date}-{##}";
StringBuilder sb = new StringBuilder(formatString);
sb.Replace("{CustomCode}", code);
sb.Replace("{Date}", date.ToString("yyyyMMdd"));
sb.Replace("{##}", count);
string result = sb.ToString();
But this is more useful if you're doing multiple replaces for the same tokens. Looks like you need String.Format as suggested by Elisha

Categories