Get string between a known string and any non-alphanumeric character - c#

I have this code which allows me to get the string between "Global." and " ".
private string getGlobalVariableName(string text)
{
int pFrom = text.IndexOf("Global.") + "Global.".Length;
int pTo = text.LastIndexOf(" ");
string name = text.Substring(pFrom, pTo - pFrom);
return name;
}
I want to modify it so that it gets the string between "Global." and any non-alphanumeric character. How could I do this?
Example:
this is true for what I have now
getGlobalVariableName(" foo Global.bar1 foobar") == "bar1"
this is what I want to be able to do
getGlobalVariableName(" foo Global.bar1>foobar") == "bar1"

You can use Regex...
string input = "Global.bar1>foobar";
var output = Regex.Match(input, #"Global.([\w]+)").Groups[1].Value;

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}";
}

Substring from character to character in C#

How can I get sub-string from one specific character to another one?
For example if I have this format:
string someString = "1.7,2015-05-21T09:18:58;";
And I only want to get this part: 2015-05-21T09:18:58
How can I use Substring from , character to ; character?
If you string has always one , and one ; (and ; after your ,), you can use combination of IndexOf and Substring like;
string someString = "1.7,2015-05-21T09:18:58;";
int index1 = someString.IndexOf(',');
int index2 = someString.IndexOf(';');
someString = someString.Substring(index1 + 1, index2 - index1 - 1);
Console.WriteLine(someString); // 2015-05-21T09:18:58
Here a demonstration.
This would be better:
string input = "1.7,2015-05-21T09:18:58;";
string output = input.Split(',', ';')[1];
Using SubString:
public string FindStringInBetween(string Text, string FirstString, string LastString)
{
string STR = Text;
string STRFirst = FirstString;
string STRLast = LastString;
string FinalString;
int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
int Pos2 = STR.IndexOf(LastString);
FinalString = STR.Substring(Pos1, Pos2 - Pos1);
return FinalString;
}
Try:
string input = "1.7,2015-05-21T09:18:58;";
string output = FindStringInBetween(input, ",", ";");
Demo: DotNet Fiddle Demo
Use regex,
#"(?<=,).*?(?=;)"
This would extract all the chars next to , symbol upto the first semicolon.

Trim a string in c# after special character

I want to trim a string after a special character..
Lets say the string is str="arjunmenon.uking". I want to get the characters after the . and ignore the rest. I.e the resultant string must be restr="uking".
How about:
string foo = str.EverythingAfter('.');
using:
public static string EverythingAfter(this string value, char c)
{
if(string.IsNullOrEmpty(value)) return value;
int idx = value.IndexOf(c);
return idx < 0 ? "" : value.Substring(idx + 1);
}
you can use like
string input = "arjunmenon.uking";
int index = input.LastIndexOf(".");
input = input.Substring(index+1, input.Split('.')[1].ToString().Length );
Use Split function
Try this
string[] restr = str.Split('.');
//restr[0] contains arjunmenon
//restr[1] contains uking
char special = '.';
var restr = str.Substring(str.IndexOf(special) + 1).Trim();
Try Regular Expression Language
using System.IO;
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "arjunmenon.uking";
string pattern = #"[a-zA-Z0-9].*\.([a-zA-Z0-9].*)";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
if (match.Groups.Count > 1)
for (int ctr = 1; ctr < match.Groups.Count; ctr++)
Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value);
}
}
}
Result:
arjunmenon.uking
Group 1: uking
Personally, I won't do the split and go for the index[1] in the resulting array, if you already know that your correct stuff is in index[1] in the splitted string, then why don't you just declare a constant with the value you wanted to "extract"?
After you make a Split, just get the last item in the array.
string separator = ".";
string text = "my.string.is.evil";
string[] parts = text.Split(separator);
string restr = parts[parts.length - 1];
The variable restr will be = "evil"
string str = "arjunmenon.uking";
string[] splitStr = str.Split('.');
string restr = splitStr[1];
Not like the methods that uses indexes, this one will allow you not to use the empty string verifications, and the presence of your special caracter, and will not raise exceptions when having empty strings or string that doesn't contain the special caracter:
string str = "arjunmenon.uking";
string restr = str.Split('.').Last();
You may find all the info you need here : http://msdn.microsoft.com/fr-fr/library/b873y76a(v=vs.110).aspx
cheers
I think the simplest way will be this:
string restr, str = "arjunmenon.uking";
restr = str.Substring(str.LastIndexOf('.') + 1);

copy character from the string in c#

Is there any way available to give start and ending value to the string and string copy all that values in c#
e.g
My name is testing.
Now i want to copy 'name is'
from the string how i can achieve. I don't have any specific length of the string, It could be increase and decrease.
Try String.IndexOf and String.Substring.
String s1 = "My name is testing.";
String sub = "name is";
int index = s1.IndexOf(sub);
String found = s2.Substring(index, sub.Length);
Well, I'm not completely sure what you are asking here, but...
I don't have any specific length of the string
Sure you do.
string s = "name is";
int len = s.Length; // len == 7
To concatenate strings you can use the + operator.
string prefix = "prefix : "
string suffix = "suffix : "
string s = prefix + "name is" + suffix;
int len = s.Length; // len == 25
I think I nailed your requirement and the solution. Do let me know if this is what you wanted and if this works!
MessageBox.Show(FindStringBetween("My name is farhan.", "My", "is"));
public string FindStringBetween(string SourceString, string StartString, string EndString)
{
int StartSelection = StartString.Length;
int EndSelection = SourceString.IndexOf(EndString)+EndString.Length;
return (SourceString.Substring(StartSelection).Substring(0, EndSelection-StartSelection));
}

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