I have a string as
"cmp197_10_27_147ee7b825-2a3b-4520-b36c-bba08f8b0d87_TempDoc_197"
I want to fetch the last digits(i.e. 197)
For obtaining same i have implemented below code
int lastUnderscore = addUcoid.LastIndexOf('_');
string getucoid = addUcoid.Substring(lastUnderscore).TrimStart('_');
The getucoid string gets the digit part properly.The problem now is that I have to also check if the digits occur in string,i.e. string can be like
"cmp197_10_27_147ee7b825-2a3b-4520-b36c-bba08f8b0d87_TempDoc"
How to perform the check on such string, whether that part(197) exists at the end in the string or not.
Here 197 is just an example.It could be any numeric data,for example 196,145,etc
string.Contains won't help: we know it is there at least once already. I would use:
int otherLocation = addUcoid.IndexOf(getucoid);
and compare this to lastUnderscore. If otherLocation is non-negative and less than lastUnderscore, then it is there in an earlier position too. You could also use:
int otherLocation = addUcoid.IndexOf(getucoid, 0, lastUnderscore);
and compare to -1; this second approach stops at the underscore, so won't find the instance from the end.
I think Regex is the easiest way. If match.Success is true the digits have been found.
Match match = System.Text.RegularExpressions.Regex.Match(addUcoid, #"(?<=_)\d+$");
if(match.Success)
{
int i = int.Parse(match.Value);
}
I suspect you just want to know if this last part is a numeric or not:
bool isNumeric = Regex.IsMatch(getucoid, #"^\d+$");
Use String.EndsWith method to findout.
http://msdn.microsoft.com/en-us/library/2333wewz%28v=vs.110%29.aspx
string s="cmp197_10_27_147ee7b825-2a3b-4520-b36c-bba08f8b0d87_TempDoc";
bool isends=s.EndsWith("197");//returns false;
s="cmp197_10_27_147ee7b825-2a3b-4520-b36c-bba08f8b0d87_TempDoc_197";
isends=s.EndsWith("197");//returns true;
The presence of a substring can be checked with String.Contains(): http://msdn.microsoft.com/en-us/library/dy85x1sa%28v=vs.110%29.aspx
Assuming you have removed the final "_197" after checking that it exists, calling Contains("197") on your string will return true if "197" is a substring, or false if it isn't.
You can use LINQ (also to check if the last char is a digit):
string str = "cmp197_10_27_147ee7b825-2a3b-4520-b36c-bba08f8b0d87_TempDoc_197";
if (Char.IsDigit(str.Last()))
{
string digits = new string(str.Reverse().TakeWhile(c => Char.IsDigit(c)).Reverse().ToArray());
}
When you say exists at the "end in the string", do you mean if it exists anywhere in the string? You can do a .Contains() to get it.
bool inTheString = addUcoid.Contains(getucoid);
Also:
FYI, your code:
int lastUnderscore = addUcoid.LastIndexOf('_');
string getucoid = addUcoid.Substring(lastUnderscore).TrimStart('_');
can be simplified shortened into:
string getucoid = addUcoid.Split('_').Last();
EDIT:
Ehm, Marc Gravell rightly points out that the string is there anyway. If you want to find out if another instance of the string is there (aside from getucoid):
int lastUnderscore = addUcoid.LastIndexOf('_');
string getucoid = addUcoid.Split('_').Last();
bool inTheString = addUcoid.Substring(0,lastUnderscore).Contains(getucoid);
Related
Is there any possibility to delete specific words from a string? For exempla
string x ="documents\bin\debug" and I want to delete "\bin\debug".
Use String.Replace():
string x = #"documents\bin\debug";
string desiredString = x.Replace(#"\bin\debug", String.Empty);
Note: The key thing here is that you have to assign the string returned by the Replace() function to a variable. (From your comment on the question, it is the problem). This can either be another variable (as in the above example) or the same variable:
string x = x.Replace(#"\bin\debug", String.Empty);
Implicitly, not assigning the return value to a variable (or using the former way) will keep the value of x, unchanged, which is the exact problem you're facing. Hope it helps :)
Use string replace
string x = #"documents\bin\debug";
string nestring = x.Replace(#"\bin\debug", "");
Console.WriteLine(nestring);
So I have this file with a number that I want to use.
This line is as follows:
TimeAcquired=1433293042
I only want to use the number part, but not the part that explains what it is.
So the output is:
1433293042
I just need the numbers.
Is there any way to do this?
Follow these steps:
read the complete line
split the line at the = character using string.Split()
extract second field of the string array
convert string to integer using int.Parse() or int.TryParse()
There is a very simple way to do this and that is to call Split() on the string and take the last part. Like so if you want to keep it as a string:
var myValue = theLineString.Split('=').Last();
If you need this as an integer:
int myValue = 0;
var numberPart = theLineString.Split('=').Last();
int.TryParse(numberPart, out myValue);
string setting=sr.ReadLine();
int start = setting.IndexOf('=');
setting = setting.Substring(start + 1, setting.Length - start);
A good approach to Extract Numbers Only anywhere they are found would be to:
var MyNumbers = "TimeAcquired=1433293042".Where(x=> char.IsDigit(x)).ToArray();
var NumberString = new String(MyNumbers);
This is good when the FORMAT of the string is not known. For instance you do not know how numbers have been separated from the letters.
you can do it using split() function as given below
string theLineString="your string";
string[] collection=theLineString.Split('=');
so your string gets divided in two parts,
i.e.
1) the part before "="
2) the part after "=".
so thus you can access the part by their index.
if you want to access numeric one then simply do this
string answer=collection[1];
try
string t = "TimeAcquired=1433293042";
t= t.replace("TimeAcquired=",String.empty);
After just parse.
int mrt= int.parse(t);
suppose there is a string like this
string temp2 = "hello";
char[] m = { 'u','i','o' };
Boolean B = temp2.Compare(m);
I want to check if the string contains my array of character or not?
I am trying but it is not taking.On compiling the message
temp2.Compare(m) should be String type
is coming.
Means it follows string.compare(string);
I hope it is not the way there should be some way to do that.
edit//
I have Corrected the line String.Compare return the Boolean Value
If what you want to determine is whether the string contains any of the characters in your array, you can use the string.IndexOfAny function.
bool containsAny = temp2.IndexOfAny(m) >= 0;
I am working on log in for my program. I am trying to prevent the user to enter a string of repeating characters such as: 111111 or aaaaaa.
How would I do this?
string str = ...
bool isValid = str.Distinct().Count() > 1;
string input = ...
bool notAllSame = input.Distinct().Skip(1).Any();
this function will tell you if you have duplicates. it checks the number of distinct characters against the original length. If they're different, you've got duplicates...
bool containsDups = "ABCDEA".Length != s.Distinct().Count();
greets,
Stefan
Edit
Found your answer here:
Testing for repeated characters in a string
I am using C# 2.0 and I have got below type of strings:
string id = "tcm:481-191820"; or "tcm:481-191820-32"; or "tcm:481-191820-8"; or "tcm:481-191820-128";
The last part of string doesn't matter i.e. (-32,-8,-128), whatever the string is it will render below result.
Now, I need to write one function which will take above string as input. something like below and will output as "tcm:0-481-1"
public static string GetPublicationID(string id)
{
//this function will return as below output
return "tcm:0-481-1"
}
Please suggest!!
If final "-1" is static you could use:
public static string GetPublicationID(string id)
{
int a = 1 + id.IndexOf(':');
string first = id.Substring(0, a);
string second = id.Substring(a, id.IndexOf('-') - a);
return String.Format("{0}0-{1}-1", first, second);
}
or if "-1" is first part of next token, try this
public static string GetPublicationID(string id)
{
int a = 1 + id.IndexOf(':');
string first = id.Substring(0, a);
string second = id.Substring(a, id.IndexOf('-') - a + 2);
return String.Format("{0}0-{1}", first, second);
}
This syntax works even for different length patterns, assuming that your string is
first_part:second_part-anything_else
All you need is:
string.Format("{0}0-{1}", id.Substring(0,4), id.Substring(4,5));
This just uses substring to get the first four characters and then the next five and put them into the format with the 0- in there.
This does assume that your format is a fixed number of characters in each position (which it is in your example). If the string might be abcd:4812... then you will have to modify it slightly to pick up the right length of strings. See Marco's answer for that technique. I'd advise using his if you need the variable length and mine if the lengths stay the same.
Also as an additional note your original function of returning a static string does work for all of those examples you provided. I have assumed there are other numbers visible but if it is only the suffix that changes then you could happily use a static string (at which point declaring a constant or something rather than using a method would probably work better).
Obligatory Regular Expression Answer:
using System.Text.RegularExpressions;
public static string GetPublicationID(string id)
{
Match m = RegEx.Match(#"tcm:([\d]+-[\d]{1})", id);
if(m.Success)
return string.Format("tcm:0-{0}", m.Groups[1].Captures[0].Value.ToString());
else
return string.Empty;
}
Regex regxMatch = new Regex("(?<prefix>tcm:)(?<id>\\d+-\\d)(?<suffix>.)*",RegexOptions.Singleline|RegexOptions.Compiled);
string regxReplace = "${prefix}0-${id}";
string GetPublicationID(string input) {
return regxMatch.Replace(input, regxReplace);
}
string test = "tcm:481-191820-128";
stirng result = GetPublicationID(test);
//result: tcm:0-481-1