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

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

Related

Retrieve and update the first number of a string

I have a string that may contain a prefix message with a number
e.g : Prefix1_SomeText
I need to check if the string contains the prefix message, and increment the number in that case.
Or if the string does not contain the prefix, I need to append it
e.g : Prefix2_SomeText.
So far I have this:
string format = "prefix{0}_";
string prefix = "prefix";
string text = "prefix1_65478516548";
if (!text.StartsWith(prefix))
{
text = text.Insert(0, string.Format(format, 1));
}
else
{
int count = int.Parse(text[6].ToString()) + 1;
text = (String.Format(format, count) + "_" + text.Substring(text.LastIndexOf('_') + 1));
}
Is there a simple way of doing it?
You could use a regular expression to check if the text contains the prefix and capture the index :
string prefix = "prefix";
string text = "prefix1_65478516548";
Regex r = new Regex($"{prefix}(\\d+)_(.*)");
var match = r.Match(text);
if (match.Success)
{
int index = int.Parse(match.Groups[1].Value);
text = $"{prefix}{index + 1}_{match.Groups[2].Value}";
}
else
{
text = $"{prefix}1_{text}";
}

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

how to increase the value of an integer in a string

Ok I currently have this code
public int i = 0; //this is outside of the private void button1_click
string str = txtEmail.Text;
int pos = str.LastIndexOf("#");
string str2 = str.Substring(pos);
string str3 = str.Substring(0, str.LastIndexOf("#"));
txtEmail.Text = str3 + i++ + str2;
it splits the email into 2 string then combines them with an integer between them, But I want it to change the integer. But that code just makes it lets saying the text becomes awesome1#email.com when i press the button to increase the 1 to a 2 it just does this instead. awesome12#email.com and so on. how do i get it to just add 1 to the 1 and not put a 2 next to the 1?
I tested the following and it looks like it solves your problem. Change this line of yours:
string str = txtEmail.Text;
To this:
string str = txtEmail.Text.Replace(string.Format("{0}#", i - 1), "#");
It sets it up so that your email addresses will be in the form of:
awesome1#email.com
awesome2#email.com
awesome3#email.com
etc.
Not sure where i is coming from in this code but hopefully this will work
string str = txtEmail.Text;
int pos = str.LastIndexOf("#");
string str2 = str.Substring(pos);
string str3 = str.Substring(0, str.LastIndexOf("#"));
txtEmail.Text = str3 + (i++).ToSting() + str2;
This should work:
String email = "awesome1#email.com";
String[] tokens = email.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
const String allowed = "0123456789";
String part1 = "";
String numberStr = "";
foreach (char c in tokens[0].Reverse())
{
if (allowed.Contains(c) && part1.Length==0)
{
numberStr += c;
}
else
{
part1 += c;
}
}
part1 = new String(part1.Reverse().ToArray());
int number = int.Parse(new String(numberStr.Reverse().ToArray()));
String result = String.Format("{0}{1}#{2}", part1, number++, tokens[1]);
Although it looks a little bit cumbersome. Accept a Regex answer if there's one.
This will work
public static string IncNumberBeforeAt(string text)
{
int lastAt = text.LastIndexOf('#');
if (lastAt != -1)
{
int pos = lastAt - 1;
string num = "";
while (text[pos] >= '0' && text[pos] <= '9')
{
num = text[pos] + num;
pos--;
if (pos < 0)
break;
}
int numInc = int.Parse(num) + 1;
return text.Replace(num.ToString() + "#", numInc.ToString() + "#");
}
else
{
return text;
}
}
test
IncNumberBeforeAt("awesome1#email.com"); // => returns awesome2#email.com
IncNumberBeforeAt("awesome234#email.com"); // => returns awesome235#email.com
IncNumberBeforeAt("email.com"); // => returns email.com
IncNumberBeforeAt("5#email.com"); // => returns 6#email.com
You will have to keep track of your original e-mail address:
e.g.
string originalEmail = "test#gmail.com";
var parts = originalEmail.Split('#');
txtEmail.Text = string.Format("{0}{1}#{2}", parts[0], i++, parts[1]);

c# Sum to string of Char array

So I have these two functions,
public static string[] CharToHex(string str, string prefix, string delimeter)
{
List<string> list = new List<string>();
foreach (char c in str)
{
list.Add(prefix + String.Format("{0:X2}",(int)c) + delimeter);
}
return list.ToArray();
}
public static string[] StrToChar(string str, string prefix, string delimeter)
{
List<string> list = new List<string>();
foreach (char c in str)
{
list.Add(prefix + (int)c + delimeter);
}
return list.ToArray();
}
Basically, I'm trying to show the Sum'd value of both returned arrays in a label.
I created a function to calculate a sum,
public static string ArraySum(int[] array)
{
string sum = array.Sum().ToString();
return sum;
}
And another function to take the string array and convert it to a string,
public static string StringArrayToString(string[] array)
{
StringBuilder builder = new StringBuilder();
foreach (string value in array)
{
builder.Append(value);
}
return builder.ToString();
}
This is how I'm putting it all together,
string[] dec = StrToChar(txtInput.Text, txtPrefix.Text, txtDelimiter.Text);
string[] hex = CharToHex(txtInput.Text, txtPrefix.Text, txtDelimiter.Text);
string decStr = StringArrayToString(dec);
string hexStr = StringArrayToString(hex);
int[] decCount = dec.Select(x => int.Parse(x)).ToArray();
int[] hexCount = hex.Select(x => int.Parse(x)).ToArray();
var builder = new StringBuilder();
Array.ForEach(decCount, x => builder.Append(x));
var res = builder.ToString();
txtDecimal.Text = decStr;
txtHex.Text = hexStr;
lblDecimalSum.Text = res;
The issue here is, this obviously isn't working, it also seems horribly inefficient, there has to be an easier way of doing all of this and also, my sum isn't properly summing up the array elements.
I'm not entirely sure how to go about doing this and any assistance / feedback would be greatly appreciated.
Thank you kindly.
If I understand you correctly, you're trying to get the add the value of each character of a string together, not parse an int from a string and add those together. If that's the case, you can do it with linq:
string x = "xasdgdfhdsfh";
int sum = x.Sum(b => b);
In fact using linq, you can accomplish everything you want to do:
string x = "xasdgdfhdsfh";
string delim = txtDelimiter.Text;
string prefix = txtPrefix.Text;
lblDecimalSum.Text = x.Sum(c => c).ToString();
txtDecimal.Text =
string.Join(delim, x.Select(c => prefix + ((int)c).ToString()));
txtHex.Text =
string.Join(delim, x.Select(c => prefix + ((int)c).ToString("X2")));

How to make a first letter capital in C#

How can the first letter in a text be set to capital?
Example:
it is a text. = It is a text.
public static string ToUpperFirstLetter(this string source)
{
if (string.IsNullOrEmpty(source))
return string.Empty;
// convert to char array of the string
char[] letters = source.ToCharArray();
// upper case the first char
letters[0] = char.ToUpper(letters[0]);
// return the array made of the new char array
return new string(letters);
}
It'll be something like this:
// precondition: before must not be an empty string
String after = before.Substring(0, 1).ToUpper() + before.Substring(1);
polygenelubricants' answer is fine for most cases, but you potentially need to think about cultural issues. Do you want this capitalized in a culture-invariant way, in the current culture, or a specific culture? It can make a big difference in Turkey, for example. So you may want to consider:
CultureInfo culture = ...;
text = char.ToUpper(text[0], culture) + text.Substring(1);
or if you prefer methods on String:
CultureInfo culture = ...;
text = text.Substring(0, 1).ToUpper(culture) + text.Substring(1);
where culture might be CultureInfo.InvariantCulture, or the current culture etc.
For more on this problem, see the Turkey Test.
If you are using C# then try this code:
Microsoft.VisualBasic.StrConv(sourceString, Microsoft.VisualBasic.vbProperCase)
I use this variant:
private string FirstLetterCapital(string str)
{
return Char.ToUpper(str[0]) + str.Remove(0, 1);
}
If you are sure that str variable is valid (never an empty-string or null), try:
str = Char.ToUpper(str[0]) + str[1..];
Unlike the other solutions that use Substring, this one does not do additional string allocations. This example basically concatenates char with ReadOnlySpan<char>.
I realize this is an old post, but I recently had this problem and solved it with the following method.
private string capSentences(string str)
{
string s = "";
if (str[str.Length - 1] == '.')
str = str.Remove(str.Length - 1, 1);
char[] delim = { '.' };
string[] tokens = str.Split(delim);
for (int i = 0; i < tokens.Length; i++)
{
tokens[i] = tokens[i].Trim();
tokens[i] = char.ToUpper(tokens[i][0]) + tokens[i].Substring(1);
s += tokens[i] + ". ";
}
return s;
}
In the sample below clicking on the button executes this simple code outBox.Text = capSentences(inBox.Text.Trim()); which pulls the text from the upper box and puts it in the lower box after the above method runs on it.
Take the first letter out of the word and then extract it to the other string.
strFirstLetter = strWord.Substring(0, 1).ToUpper();
strFullWord = strFirstLetter + strWord.Substring(1);
text = new String(
new [] { char.ToUpper(text.First()) }
.Concat(text.Skip(1))
.ToArray()
);
this functions makes capital the first letter of all words in a string
public static string FormatSentence(string source)
{
var words = source.Split(' ').Select(t => t.ToCharArray()).ToList();
words.ForEach(t =>
{
for (int i = 0; i < t.Length; i++)
{
t[i] = i.Equals(0) ? char.ToUpper(t[i]) : char.ToLower(t[i]);
}
});
return string.Join(" ", words.Select(t => new string(t)));;
}
string str = "it is a text";
// first use the .Trim() method to get rid of all the unnecessary space at the begining and the end for exemple (" This string ".Trim() is gonna output "This string").
str = str.Trim();
char theFirstLetter = str[0]; // this line is to take the first letter of the string at index 0.
theFirstLetter.ToUpper(); // .ToTupper() methode to uppercase the firstletter.
str = theFirstLetter + str.substring(1); // we add the first letter that we uppercased and add the rest of the string by using the str.substring(1) (str.substring(1) to skip the first letter at index 0 and only print the letters from the index 1 to the last index.)
Console.WriteLine(str); // now it should output "It is a text"
static String UppercaseWords(String BadName)
{
String FullName = "";
if (BadName != null)
{
String[] FullBadName = BadName.Split(' ');
foreach (string Name in FullBadName)
{
String SmallName = "";
if (Name.Length > 1)
{
SmallName = char.ToUpper(Name[0]) + Name.Substring(1).ToLower();
}
else
{
SmallName = Name.ToUpper();
}
FullName = FullName + " " + SmallName;
}
}
FullName = FullName.Trim();
FullName = FullName.TrimEnd();
FullName = FullName.TrimStart();
return FullName;
}
string Input = " it is my text";
Input = Input.TrimStart();
//Create a char array
char[] Letters = Input.ToCharArray();
//Make first letter a capital one
string First = char.ToUpper(Letters[0]).ToString();
//Concatenate
string Output = string.Concat(First,Input.Substring(1));
Try this code snippet:
char nm[] = "this is a test";
if(char.IsLower(nm[0])) nm[0] = char.ToUpper(nm[0]);
//print result: This is a test

Categories

Resources