How to fix parsing int from string? - c#

I am trying to get the percent at the end of a string (i.e. "50013 / 247050 [20%]" I would want the 20 at the end.) for some reason it keeps returning -1. What is the problem with my code?
public int percent(String s)
{
String outp = "-1";
if(s != null)
outp = s;
try
{
outp = s.Substring(s.IndexOf("["), s.IndexOf("%"));
}
catch (ArgumentOutOfRangeException e)
{
}
int outt = int.Parse(outp);
return outt;
}

The second parameter isn't a index but a count. So you should do something like this:
// because, you don't want the [, you'll add 1 to the index,
int index1 = s.IndexOf("[") + 1;
int index2 = s.IndexOf("%");
string outp = s.Substring(index1, index2 - index1);

You can also use regex for this
string text = "50013 / 247050 [20%]";
var outp = Regex.Match(text, #"\[(\d+)%\]").Groups[1].Value;

Related

Improving code string processing

I have this string:
var string1 = numericUpDown2.Text; // 1
always want to contain 4 numbers like 0001 or for "11" = 0011.
I used this code to make it:
private string Corection4(string variable)
{
var stringlen = variable.Length;
if (stringlen < 2)
{
string corectvariable = "000" + variable;
return corectvariable;
}
if (stringlen < 3)
{
string corectvariable = "00" + variable;
return corectvariable;
}
if (stringlen < 4)
{
string corectvariable = "0" + variable;
return corectvariable;
}
else
{
string corectvariable = variable;
return corectvariable;
}
}
Now i need some help to improve this code
You can make it easy by ToString() method. For example:
var correctVariable = variable.ToString("D4");
It would add extra zeros to your string.
If you are working on strings, parse it first to int value:
var correctVariable = string.Format("{0:D4}", int.Parse(variable));
You can use String.Format()
int number = 11;
//D4 = pad with 0000
string outputValue = String.Format("{0:D4}", number);

c# regular expression getting specific string from string[CLOSE]

help i want to get the specific string from my string x="Glass 1 1000"; i want to get the string "Glass" only and save it to my string type.
int[] quanvalue = new int[2];
int x1 = 0;
string type = "";
string x="Glass 1 1000";
string[] numbers = Regex.Split(x, #"\D+");
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int ib = int.Parse(value);
quanvalue[x1] = ib;
MessageBox.Show(quanvalue[0].ToString() + " " + quanvalue[1].ToString());
x1++;
}
else
{
// i want to get string from here
}
string sub = x.Substring(0, 5);
You can use a substring function to fetch the first 5 characters from x.
And save it in x itself

Split numeric and Non-Numeric in a String

If I have a string value like this "1234-", then I need to split till the non-numeric character that is - and add numeric value 1 after the non-numeric char. later I have to update the value to "1234-1". Then the program will check with the last updated value 1234-1 then it will increment by 1 every time and store it for future use. If no non-numeric in a string then the program will increment by 1 with the numeric string.
Below are some examples of String and Output Value
Ex Str1 Output
2014- 2014-1
2014-1 2014-2
AAA AAA1
ABC-ABC ABC-ABC1
12345 12346
1234AA 1234AA1
I have used the below code before.
Code
var SiteFile = (from site in db.SiteFiles where site.Code == "ACQPONUM" select site.Line2).FirstOrDefault(); // Get Input string to generate AUTO number.
int Count = (from Porders in db.Porders where Porders.No.StartsWith(SiteFile) select Porders.No).ToList().Count; // Get the count of matching values in db.
var PONo = (from Porders in db.Porders where Porders.No.StartsWith(SiteFile) select Porders.No).ToList(); // Get list of Matching existing values.
if (Count != 0)
{
if (PONo != null)
{
int Val = (from PONos in PONo let value = Regex.Match(PONos, #"\d+").Value select Convert.ToInt32(value == string.Empty ? "0" : Regex.Match(PONos, #"\d+").Value) + 1).Concat(new[] { 0 }).Max(); // Fiind the maximum value in the matched list nd Increment value by if same type exists in the db.
porder.No = SiteFile + Val.ToString();
}
}
else
{
porder.No = SiteFile + "1";
}
Any help to this will be appreciated.
Maybe something like this:
string s = "123419";
string res = null;
char ch = s[s.Length - 1];
if(char.IsDigit(ch)) // handle numbers
{
res = s.Substring(0,s.Length - 1);
string suffix = null;
// special case
if(ch == '9'){
suffix = "10";
}
else
{
suffix = (++ch).ToString();
}
res += suffix;
}
else
{
res = string.Format("{0}1", s);
}
Try this code:
private string Incrementvalue(string str)
{
string retVal;
if (str.Contains(DELIMITER))
{
string[] parts = str.Split(new char[] { DELIMITER }, 2);
string origSuffix = parts[1];
string newSuffix;
int intSuffix;
if (int.TryParse(origSuffix, out intSuffix))
//Delimiter exists and suffix is already a number: Increment!
newSuffix = (intSuffix + 1).ToString();
else
//Delimiter exists and suffix is NTO number: Add a "1" suffix.
newSuffix = origSuffix + 1;
retVal = parts[0] + DELIMITER + newSuffix;
}
else
{
int temp;
if (int.TryParse(str, out temp))
{
//Delimiter does not exists and the input is a number: Increment last digit!
string newSuffix = (int.Parse(str[str.Length - 1].ToString()) + 1).ToString();
retVal = str.Substring(0, str.Length - 1) + newSuffix;
retVal = str.Substring(0, str.Length - 1) + newSuffix;
}
else
{
//Delimiter does not exists and the input is NOT a number: Add a "1" suffix.
retVal = str + "1";
}
}
return retVal;
}
The code could be written in a much more compact manner, but think this will be more readable and it will work...

Find text in string with C#

How can I find given text within a string? After that, I'd like to create a new string between that and something else. For instance, if the string was:
This is an example string and my data is here
And I want to create a string with whatever is between "my " and " is" how could I do that? This is pretty pseudo, but hopefully it makes sense.
Use this method:
public static string getBetween(string strSource, string strStart, string strEnd)
{
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
int Start, End;
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
return "";
}
How to use it:
string source = "This is an example string and my data is here";
string data = getBetween(source, "my", "is");
This is the simplest way:
if(str.Contains("hello"))
You could use Regex:
var regex = new Regex(".*my (.*) is.*");
if (regex.IsMatch("This is an example string and my data is here"))
{
var myCapturedText = regex.Match("This is an example string and my data is here").Groups[1].Value;
Console.WriteLine("This is my captured text: {0}", myCapturedText);
}
string string1 = "This is an example string and my data is here";
string toFind1 = "my";
string toFind2 = "is";
int start = string1.IndexOf(toFind1) + toFind1.Length;
int end = string1.IndexOf(toFind2, start); //Start after the index of 'my' since 'is' appears twice
string string2 = string1.Substring(start, end - start);
Here's my function using Oscar Jara's function as a model.
public static string getBetween(string strSource, string strStart, string strEnd) {
const int kNotFound = -1;
var startIdx = strSource.IndexOf(strStart);
if (startIdx != kNotFound) {
startIdx += strStart.Length;
var endIdx = strSource.IndexOf(strEnd, startIdx);
if (endIdx > startIdx) {
return strSource.Substring(startIdx, endIdx - startIdx);
}
}
return String.Empty;
}
This version does at most two searches of the text. It avoids an exception thrown by Oscar's version when searching for an end string that only occurs before the start string, i.e., getBetween(text, "my", "and");.
Usage is the same:
string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");
You can do it compactly like this:
string abc = abc.Replace(abc.Substring(abc.IndexOf("me"), (abc.IndexOf("is", abc.IndexOf("me")) + 1) - abc.IndexOf("size")), string.Empty);
Except for #Prashant's answer, the above answers have been answered incorrectly. Where is the "replace" feature of the answer? The OP asked, "After that, I'd like to create a new string between that and something else".
Based on #Oscar's excellent response, I have expanded his function to be a "Search And Replace" function in one.
I think #Prashant's answer should have been the accepted answer by the OP, as it does a replace.
Anyway, I've called my variant - ReplaceBetween().
public static string ReplaceBetween(string strSource, string strStart, string strEnd, string strReplace)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
string strToReplace = strSource.Substring(Start, End - Start);
string newString = strSource.Concat(Start,strReplace,End - Start);
return newString;
}
else
{
return string.Empty;
}
}
static void Main(string[] args)
{
int f = 0;
Console.WriteLine("enter the string");
string s = Console.ReadLine();
Console.WriteLine("enter the word to be searched");
string a = Console.ReadLine();
int l = s.Length;
int c = a.Length;
for (int i = 0; i < l; i++)
{
if (s[i] == a[0])
{
for (int K = i + 1, j = 1; j < c; j++, K++)
{
if (s[K] == a[j])
{
f++;
}
}
}
}
if (f == c - 1)
{
Console.WriteLine("matching");
}
else
{
Console.WriteLine("not found");
}
Console.ReadLine();
}
string WordInBetween(string sentence, string wordOne, string wordTwo)
{
int start = sentence.IndexOf(wordOne) + wordOne.Length + 1;
int end = sentence.IndexOf(wordTwo) - start - 1;
return sentence.Substring(start, end);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
namespace oops3
{
public class Demo
{
static void Main(string[] args)
{
Console.WriteLine("Enter the string");
string x = Console.ReadLine();
Console.WriteLine("enter the string to be searched");
string SearchText = Console.ReadLine();
string[] myarr = new string[30];
myarr = x.Split(' ');
int i = 0;
foreach(string s in myarr)
{
i = i + 1;
if (s==SearchText)
{
Console.WriteLine("The string found at position:" + i);
}
}
Console.ReadLine();
}
}
}
This is the correct way to replace a portion of text inside a string (based upon the getBetween method by Oscar Jara):
public static string ReplaceTextBetween(string strSource, string strStart, string strEnd, string strReplace)
{
int Start, End, strSourceEnd;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
strSourceEnd = strSource.Length - 1;
string strToReplace = strSource.Substring(Start, End - Start);
string newString = string.Concat(strSource.Substring(0, Start), strReplace, strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start));
return newString;
}
else
{
return string.Empty;
}
}
The string.Concat concatenates 3 strings:
The string source portion before the string to replace found - strSource.Substring(0, Start)
The replacing string - strReplace
The string source portion after the string to replace found - strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start)
Simply add this code:
if (string.Contains("search_text")) {
MessageBox.Show("Message.");
}
If you know that you always want the string between "my" and "is", then you can always perform the following:
string message = "This is an example string and my data is here";
//Get the string position of the first word and add two (for it's length)
int pos1 = message.IndexOf("my") + 2;
//Get the string position of the next word, starting index being after the first position
int pos2 = message.IndexOf("is", pos1);
//use substring to obtain the information in between and store in a new string
string data = message.Substring(pos1, pos2 - pos1).Trim();
First find the index of text and then substring
var ind = Directory.GetCurrentDirectory().ToString().IndexOf("TEXT To find");
string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
I have different approach on ReplaceTextBetween() function.
public static string ReplaceTextBetween(this string strSource, string strStart, string strEnd, string strReplace)
{
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
var startIndex = strSource.IndexOf(strStart, 0) + strStart.Length;
var endIndex = strSource.IndexOf(strEnd, startIndex);
var strSourceLength = strSource.Length;
var strToReplace = strSource.Substring(startIndex, endIndex - startIndex);
var concatStart = startIndex + strToReplace.Length;
var beforeReplaceStr = strSource.Substring(0, startIndex);
var afterReplaceStr = strSource.Substring(concatStart, strSourceLength - endIndex);
return string.Concat(beforeReplaceStr, strReplace, afterReplaceStr);
}
return strSource;
}
Correct answer here without using any pre-defined method.
static void WordContainsInString()
{
int f = 0;
Console.WriteLine("Input the string");
string str = Console.ReadLine();
Console.WriteLine("Input the word to search");
string word = Console.ReadLine();
int l = str.Length;
int c = word.Length;
for (int i = 0; i < l; i++)
{
if (str[i] == word[0])
{
for (int K = i + 1, j = 1; j < c; j++, K++)
{
if (str[K] == word[j])
{
f++;
}
else
{
f = 0;
}
}
}
}
if (f == c - 1)
{
Console.WriteLine("matching");
}
else
{
Console.WriteLine("not found");
}
Console.ReadLine();
}
for .net 6 can use next code
public static string? Crop(string? text, string? start, string? end = default)
{
if (text == null) return null;
string? result;
var startIndex = string.IsNullOrEmpty(start) ? 0 : text.IndexOf(start);
if (startIndex < 0) return null;
startIndex += start?.Length ?? 0;
if (string.IsNullOrEmpty(end))
{
result = text.Substring(startIndex);
}
else
{
var endIndex = text.IndexOf(end, startIndex);
if (endIndex < 0) return null;
result = text.Substring(startIndex, endIndex - startIndex);
}
return result;
}

finding an string expression in an sentence

I have like a three word expression: "Shut The Door" and I want to find it in a sentence. Since They are kind of seperated by space what would be the best solution for it.
If you have the string:
string sample = "If you know what's good for you, you'll shut the door!";
And you want to find where it is in a sentence, you can use the IndexOf method.
int index = sample.IndexOf("shut the door");
// index will be 42
A non -1 answer means the string has been located. -1 means it does not exist in the string. Please note that the search string ("shut the door") is case sensitive.
Use build in Regex.Match Method for matching strings.
string text = "One car red car blue car";
string pat = #"(\w+)\s+(car)";
// Compile the regular expression.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
int matchCount = 0;
while (m.Success)
{
Console.WriteLine("Match"+ (++matchCount));
for (int i = 1; i <= 2; i++)
{
Group g = m.Groups[i];
Console.WriteLine("Group"+i+"='" + g + "'");
CaptureCollection cc = g.Captures;
for (int j = 0; j < cc.Count; j++)
{
Capture c = cc[j];
System.Console.WriteLine("Capture"+j+"='" + c + "', Position="+c.Index);
}
}
m = m.NextMatch();
}
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.match(v=vs.71).aspx
http://support.microsoft.com/kb/308252
if (string1.indexOf(string2) >= 0)
...
The spaces are nothing special, they are just characters, so you can find a string like this like yuo would find any other string in your sentence, for example using "indexOf" if you need the position, or just "Contains" if you need to know if it exists or not.
E.g.
string sentence = "foo bar baz";
string phrase = "bar baz";
Console.WriteLine(sentence.Contains(phrase)); // True
Here is some C# code to find a substrings using a start string and end string point but you can use as a base and modify (i.e. remove need for end string) to just find your string...
2 versions, one to just find the first instance of a substring, other returns a dictionary of all starting positions of the substring and the actual string.
public Dictionary<int, string> GetSubstringDic(string start, string end, string source, bool includeStartEnd, bool caseInsensitive)
{
int startIndex = -1;
int endIndex = -1;
int length = -1;
int sourceLength = source.Length;
Dictionary<int, string> result = new Dictionary<int, string>();
try
{
//if just want to find string, case insensitive
if (caseInsensitive)
{
source = source.ToLower();
start = start.ToLower();
end = end.ToLower();
}
//does start string exist
startIndex = source.IndexOf(start);
if (startIndex != -1)
{
//start to check for each instance of matches for the length of the source string
while (startIndex < sourceLength && startIndex > -1)
{
//does end string exist?
endIndex = source.IndexOf(end, startIndex + 1);
if (endIndex != -1)
{
//if we want to get length of string including the start and end strings
if (includeStartEnd)
{
//make sure to include the end string
length = (endIndex + end.Length) - startIndex;
}
else
{
//change start index to not include the start string
startIndex = startIndex + start.Length;
length = endIndex - startIndex;
}
//add to dictionary
result.Add(startIndex, source.Substring(startIndex, length));
//move start position up
startIndex = source.IndexOf(start, endIndex + 1);
}
else
{
//no end so break out of while;
break;
}
}
}
}
catch (Exception ex)
{
//Notify of Error
result = new Dictionary<int, string>();
StringBuilder g_Error = new StringBuilder();
g_Error.AppendLine("GetSubstringDic: " + ex.Message.ToString());
g_Error.AppendLine(ex.StackTrace.ToString());
}
return result;
}
public string GetSubstring(string start, string end, string source, bool includeStartEnd, bool caseInsensitive)
{
int startIndex = -1;
int endIndex = -1;
int length = -1;
int sourceLength = source.Length;
string result = string.Empty;
try
{
if (caseInsensitive)
{
source = source.ToLower();
start = start.ToLower();
end = end.ToLower();
}
startIndex = source.IndexOf(start);
if (startIndex != -1)
{
endIndex = source.IndexOf(end, startIndex + 1);
if (endIndex != -1)
{
if (includeStartEnd)
{
length = (endIndex + end.Length) - startIndex;
}
else
{
startIndex = startIndex + start.Length;
length = endIndex - startIndex;
}
result = source.Substring(startIndex, length);
}
}
}
catch (Exception ex)
{
//Notify of Error
result = string.Empty;
StringBuilder g_Error = new StringBuilder();
g_Error.AppendLine("GetSubstring: " + ex.Message.ToString());
g_Error.AppendLine(ex.StackTrace.ToString());
}
return result;
}
You may want to make sure the check ignores the case of both phrases.
string theSentence = "I really want you to shut the door.";
string thePhrase = "Shut The Door";
bool phraseIsPresent = theSentence.ToUpper().Contains(thePhrase.ToUpper());
int phraseStartsAt = theSentence.IndexOf(
thePhrase,
StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine("Is the phrase present? " + phraseIsPresent);
Console.WriteLine("The phrase starts at character: " + phraseStartsAt);
This outputs:
Is the phrase present? True
The phrase starts at character: 21

Categories

Resources