How to get text contained between brackets [duplicate] - c#

This question already has answers here:
How do I extract text that lies between parentheses (round brackets)?
(19 answers)
Closed 8 years ago.
I have 3 different string values in my console application:
Student A (AA.1)
Student(1) B (AA.2)
Student B
Would like to get value from backet:
AA.1, AA.2
Thanks. I have used split, however will encounter error because of Student B does not have any bracket and Student(1) B (AA.2) have 2 brackets.
Current Code
char[] targetExpression = new char[] { '(', ')' };
string title = "Student A (AA.1)";
Console.WriteLine(title.Split(targetExpression)[1]);

looking for something like this?
/.*\(([^)]*)\)$/

A function to get a string within characters
string GetStirngWithiin(string SourceString, char startChar, char endChar,int StartFrom=0)
{
SourceString = SourceString.Substring(StartFrom);
int startFrom=SourceString.IndexOf(startChar);
int EndAt=SourceString.IndexOf(endChar);
if ((startFrom > -1) && (EndAt >-1))
{
int SubStrLength = EndAt - startFrom - 1;
if (SubStrLength > 0)
{
string Result = SourceString.Substring(startFrom + 1, SubStrLength);
return Result;
}
}
return "";
}
you can use the function calls as
string str1 = GetStirngWithiin("Student A (AA.1)",'(',')');
string str2 = GetStirngWithiin("Student(1) B (AA.2))", '(', ')',10);
using with Student B will return a blank string.

Related

How to check if a string ends with a number, without regex? [duplicate]

This question already has answers here:
Extract number at end of string in C#
(9 answers)
Regex for number at the end of string?
(5 answers)
Closed 3 years ago.
I need to check if the last character of a string ends with an int. I would like to avoid using a regular expression, because I think it is very hard, but if there is no smoother way of doing it, I will try it.
I basically tried something that looks like this:
text.EndsWith(INTEGER)]
Boolean result = char.IsDigit(text[text.Length - 1]);
using linq Last method and Isdigit function
bool isDigit = Char.IsDigit(("one1").Last());
Isolate the last character and try parse it to integer:
private static bool IsStringEndsWithDigit(string str)
{
if (String.IsNullOrEmpty(str))
{
return false;
// or throw an exception
// throw new Exception("string can not be empty");
}
string last = str.Substring(str.Length - 1, 1);
int num;
var isNum = int.TryParse(last, out num);
return isNum;
}
var lastChar = text.Last();
var endsWithNum = lastChar >= '0' && lastChar <= '9';
string s = "hello world0";
int len = s.Length;
List<char> digits = new List<char>(){'0','1','2','3','4','5','6','7','8','9'};
if (digits.Contains(s[len - 1]))
{
Console.WriteLine("last character is digits");
}

how to create int to string like this 50-> "00050" [duplicate]

This question already has answers here:
Convert int (number) to string with leading zeros? (4 digits) [duplicate]
(4 answers)
Closed 5 years ago.
Hello i am trying to process character arrays.
I want to assign the number 50 as string value "00050". How can I do it ?
enter code here
string strRpc(int NumstrRpcSendLen)
{
int digit = Convert.ToInt32( Math.Floor(Math.Log10(NumstrRpcSendLen + 5) + 1));
int len = 0;
char[] d = new char[5];
string result= null;
while (len<5)
{
if (len<digit)
{
d[len] = '0';
}
else
{
}
len++;
}
return result;
}
I'm not sure what your code is doing, but there's a string format specifier for that:
var x = 50.ToString("D5");
//x = "000050"
Look at the documentation for more help
You could try it
var result = 50.ToString("00000");

Separating words in a string based on empty spaces with c# [duplicate]

This question already has answers here:
Split string and remove spaces without .select
(2 answers)
Closed 6 years ago.
I have strings like this:
string mystring = "12353 90123B41094 A01283410294 3"
I need to separate this string that has 3 or 4 strings separated by empty spaces.
Here is my attempt:
string block = "";
Arraytext = text.ToCharArray();
for(int i = 0; i <= text.Length; i++)
{
while (Arraytext[i] !=' ') { block = block + Arraytext[i]; counter++; } // also tried Arraytext[i] != '/0'
}
while (Arraytext [counter] == ' ')counter++; //to get where the next string begins
//repeat this function until the strings has been obtained
This doesn't work:
The string block is filled with 0
The Arraytext doesn't detect the empty spaces so the loop runs the entire string. I have tried ' ' and '/0'
To seperate the words between the spaces you can use
string mystring = "12353 90123B41094 A01283410294 3";
string[] result = mystring.Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);

How to find out the duplicate characters in a string? [duplicate]

This question already has answers here:
How do I get an array of repeated characters from a string using LINQ?
(3 answers)
Closed 7 years ago.
I take a string with integer count
int count=0;
string s="wow"
and i am using foreach loop to count number of characters in a specified string
foreach(char ch in s)
{
count++
}
so how can i count those characters which are repeated in my string like 'w'.
Try this )
string test = "aababc";
var result = test.GroupBy(c => c).Where(c => c.Count() > 1).Select(c => new { charName = c.Key, charCount = c.Count()});
Do like this
string s="wow";
int repeats= s.Length - s.ToCharArray().Distinct().Count();

Having an issue with trimming a string in C# [duplicate]

This question already has answers here:
Get string between two strings in a string
(27 answers)
Closed 7 years ago.
I have a problem about trimming below word in C#
For example, I got a string = "StackLevelTwoItem" and I need to pull the "Two" or "Three" out of this string.
StackLevelTwoItem -> I should get "Two"
StackLevelThreeItem -> I should get "Three"
... and so on ...
Can anybody help?
Thank you
For the two examples given:
const string prefix = "StackLevel";
const string suffix = "Item";
public static string GetCentralPart(string str)
{
if (str == null)
{
return str;
}
if (!str.StartsWith(prefix) || !str.EndsWith(suffix))
{
return str;
}
return str.Substring(prefix.Length, str.Length - prefix.Length - suffix.Length);
}
Use:
string str = "StackLevelThreeItem";
string centralPart = GetCentralPart(str);
The code is quite linear... The only interesting points are the use of some const string for the prefix/suffix, the use of StartsWith/EndsWith to check that the string really has the prefix/suffix, and how the Substring length is calculated.
i would use RegEx for this Case
string Result = Regex.Match("StackLevelOneItem", #"(?<=StackLevel)[\w]*(?=Item)").Value;
Here is an example using Regex.
static void Main(string[] args)
{
var l2 = GetLevel("StackLevelTwoItem"); // returns "Two"
var l3 = GetLevel("StackLevelThreeItem"); // returns "Three"
var l1 = GetLevel("StackLvlOneItem"); // returns empty string
}
static string GetLevel(string input)
{
var pattern = "StackLevel(.*)Item";
var match = Regex.Match(input, pattern);
if (match.Groups[1].Success)
return match.Groups[1].Value;
else
return String.Empty;
}

Categories

Resources