Get values between string in C# [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a string value like "%2%,%12%,%115%+%55%,..."
Sample inputs "(%2%+%5%)/5"
Step1:
get the vales 2 and 5
Step2:
get values from table column2 and column5
step3:
from that value (Column2+Column5)/5
How to get the values from that string
2,12,115,55
Also
commas, "+" (symbols)
Thanks in Advance.
I referred these links:
Find a string between 2 known values
How do I extract text that lies between parentheses (round brackets)?

You can replace the % and then split on the , and +:
var value = "%2%,%12%,%115%+%55%,";
value = value.Replace("%", "");
var individualValues = value.Split(new[] {',', '+'});
foreach (var val in individualValues)
Console.WriteLine(val);

If I understand you correctly...
var string = "%2%,%12%,%115%+%55%";
var values = string.replace("%", "").replace("+", "").split(',');
Edit: Actually, I think you mean you want to split on "+" so that becomes split(',', '+')

str.Replace("%", "").Replace("+",",").Split(',');
This will do it.
Another regex solution:
foreach (Match m in Regex.Matches(str, #"\d+"))
// m.Value is the values you wanted

Using regular expressions:
using System.Text.RegularExpressions;
Regex re = new Regex("\\d+");
MatchCollection matches = re.Matches("%2%,%12%,%115%+%55%,...");
List<int> lst = new List<int>();
foreach (Match m in matches)
{
lst.Add(Convert.ToInt32(m.Value));
}

It's possible parsing the string with splits and other stuff or through Regex:
[TestMethod]
public void TestGetNumberCommasAndPlusSign()
{
Regex r = new Regex(#"[\d,\+]+");
string result = "";
foreach (Match m in r.Matches("%2%,%12%,%115%+%55%,..."))
result += m.Value;
Assert.AreEqual("2,12,115+55,", result);
}

Related

Splitting a string into characters, but keeping some together [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have this string: TF'E'
I want to split it to characters, but the '" character should join the character before it.
So it would look like this: T, F' and E'
You could use a regular expression to split the string at each position immediately before a new letter and an optional ':
var input = "TF'E'";
var output = Regex.Split(input, #"(?<!^)(?=\p{L}'?)");
output will now be a string array like ["T", "F'", "E'"]. The lookbehind (?<!^) ensure we never split at the start of the string, whereas the lookahead (?=\p{L}'?) describes one letter \p{L} followed by 0 or 1 '.
You can use a regex to capture "an uppercase character followed optionally by an apostrophe"
var mc = Regex.Matches(input, "(?<x>[A-Z]'?)");
foreach(Match m in mc)
Console.WriteLine(m.Groups["x"].Value);
If you don't like regex, you can use this method:
public static IEnumerable<string> Split(string input)
{
for(int i = 0; i < input.Length; i++)
{
if(i != (input.Length - 1) && input[i+1] == '\'')
{
yield return input[i].ToString() + input[i+1].ToString();
i++;
}
else
{
yield return input[i].ToString();
}
}
}
We loop through the input string. We check if there is a next character and if it is a '. If true, return the current character and the next character and increase the index by one. If false, just return the current character.
Online demo: https://dotnetfiddle.net/sPCftB

Getting two numbers which are separated by colon [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last month.
Improve this question
I got a bit of a problem. I'm trying to split some text and numbers.
Considering this string input.
string input = "1 Johannes 1:3, 2 Johannes 2:6, 1 Mosebok 5:4";
I'm trying to get the 2:3, 2:6, 5:4 to split from the rest of the text.
Then I want them to be separated from the colon, and be added to a list.
The list would look like this, after being looped out.
2
3
2
6
5
4
In which I could create a Hashtable entry from [0] and [1], [2] and [3], [4] and [5].
I would like to thank you all for your feedback on this.
If I understand your question correctly, I would do it as
string input = "1 Johannes 1:3, 2 Johannes 2:6, 1 Mosebok 5:4";
var table = Regex.Matches(input, #"(\d+):(\d+)")
.Cast<Match>()
.ToLookup(m => m.Groups[1].Value, m => m.Groups[2].Value);
Use Regex
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "1 Johannes 1:3, 2 Johannes 2:6, 1 Mosebok 5:4";
string pattern = #"(?'index'\d+)\s+(?'name'\w+)\s+(?'para'\d+:\d+),?";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine("index : {0}, name : {1}, para : {2}",
match.Groups["index"],
match.Groups["name"],
match.Groups["para"]
);
}
Console.ReadLine();
}
}
}
Here some piece of code that can help you.
var input = "1 Johannes 1:3, 2 Johannes 2:6, 1 Mosebok 5:4";
var nextIndex = 0;
var currentIndex = 0;
var numbers = new List<int>();
do
{
currentIndex = input.IndexOf(":", currentIndex + 1);
var leftNumber = Convert.ToInt32(input[currentIndex - 1].ToString());
var rightNumber = Convert.ToInt32(input[currentIndex + 1].ToString());
numbers.Add(leftNumber);
numbers.Add(rightNumber);
nextIndex = input.IndexOf(":", currentIndex + 1);
} while (nextIndex != -1);

How can I return the index of the second word in a string that can have multiple white spaces followed by one word followed by multiple white spaces? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
String str =" vol ABCD C XYZ";
I want to return the index of "A"
Note: There are multiple white spaces before all words including the first.
This will get the index of A in your original example (String str =" vol ABCD C XYZ";):
int indexOfABCD = str.IndexOf(str.Trim()[str.Trim().IndexOf(' ')+1]);
If you have something like String str = " vol ABCD C XYZ"; where there are multiple spaces:
string secondword = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)[1];
int indexOfAinABCD = str.IndexOf(secondword.First());
If you want to get the indices of all the letters in the second word:
IEnumerable<int> fullindex = Enumerable.Range(indexOfAinABCD, secondword.Length);
EDIT:
This will fail if you have A anywhere else in the first word. You should get an exact match through Regex:
int indexOfAinABCD = Regex.Match(str, string.Format(#"\W{0}\W",secondword)).Index+1;
IEnumerable<int> fullindex = Enumerable.Range(indexOfAinABCD, secondword.Length);
So something like String str = " vABCDol ABCD C XYZ"; won't be an issue

How can I return a string between two other strings in C#? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string for a page source already created. I need to grab a few lines of text from the string. The string I need is between two other strings. These two strings are "keywords": and ", "
How would I search for a string that has a colon after the quotations such as "keywords":
?
Would I use regex?
Thank you.
In your case, regex is too powerful to use it with such a problem. Just use string.IndexOf() and string.Substring(). Get a position of the word, get a position of the closest comma - there is an overload for this in IndexOf that let you specify starting position of searching.
Here is a code snippet, it is more explaining then I could do it in words.
var text = "\"keywords\":some text you want,and a text you do not want";
var searchFor = "\"keywords\":";
int firstIndex = text.IndexOf(searchFor);
int secondIndex = text.IndexOf(",", firstIndex);
var result = text.Substring(firstIndex + searchFor.Length, secondIndex - searchFor.Length);
The following Regex will match everything between "keywords" and ",":
Regex r = new Regex("keywords:(.*),");
Match m = r.Match(yourStringHere);
foreach(Group g in m.Groups) {
// do your work here
}
You can try like this, without using Regex
string str = "This is an example string and my data is here";
string first = "keywords:";
string second = ",";
int Start, End;
if (str.Contains(first) && str.Contains(second))
{
Start = str.IndexOf(first, 0) + first.Length;
End = str.IndexOf(second, Start);
return str.Substring(Start, End - Start);
}
else
{
return "";
}
This ought to work across multiple lines.
string input = #"blah blah blah ""keywords"":this is " + Environment.NewLine + "what you want right?, more blah...";
string pattern = #"""keywords"":(.*),";
Match match = Regex.Match(input, pattern, RegexOptions.Singleline);
if (match.Success)
{
string stuff = match.Groups[1].Value;
}

How to find the capital substring of a string? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to find the capitalized portion of a string, to then insert two characters that represent the Double Capital sign in the Braille language. My intention for doing this is to design a translator that can translate from regular text to Braille.
I'll give an example belo.
English String: My variable is of type IEnumerable.
Braille: ,My variable is of type ,,IE-numberable.
I also want the dash in IE-numerable to only break words that have upper and lower case, but not in front of punctuation marks, white spaces, numbers or other symbols.
Thanks a lot in advance for your answers.
I had never heard of a "Double Capital" sign, so I read up on it here. From what I can tell, this should suit your needs.
You can use this to find any sequence of two or more uppercase (majuscule) Latin letters or hyphens in your string:
var matches = Regex.Matches(input, "[A-Z-]{2,}");
You can use this to insert the double-capital sign:
var result = Regex.Replace(input, "[A-Z-]{2,}", ",,$0");
For example:
var input = "this is a TEST";
var result = Regex.Replace(input, "[A-Z-]{2,}", ",,$0"); // this is a ,,TEST
You can use this to hand single and double capitals:
var input = "McGRAW-HILL";
var result = Regex.Replace(input, "[A-Z-]([A-Z-]+)?",
m => (m.Groups[1].Success ? ",," : ",") + m.Value); // ,Mc,,GRAW-HILL
You can find them with a simple regex:
using System.Text.RegularExpressions;
// ..snip..
Regex r = new Regex("[A-Z]"); // This will capture only upper case characters
Match m = r.Match(input, 0);
The variable m of type System.Text.RegularExpressions.Match will contain a collection of captures. If only the first match matters, you can check its Index property directly.
Now you can insert the characters you want in that position, using String.Insert:
input = input.Insert(m.Index, doubleCapitalSign);
this code can solve your problema
string x = "abcdEFghijkl";
string capitalized = string.Empty;
for (int i = 0; i < x.Length; i++)
{
if (x[i].ToString() == x[i].ToString().ToUpper())
capitalized += x[i];
}
Have you tried using the method Char.IsUpper method
http://msdn.microsoft.com/en-us/library/9s91f3by.aspx
This is another similar question that uses that method to solve a similar problem
Get the Index of Upper Case letter from a String
If you just want to find the first index of an uppercase letter:
var firstUpperCharIndex = text // <-- a string
.Select((chr, index) => new { chr, index })
.FirstOrDefault(x => Char.IsUpper(x.chr));
if (firstUpperCharIndex != null)
{
text = text.Insert(firstUpperCharIndex.index, ",,");
}
Not sure if this is what you are going for?
var inputString = string.Empty; //Your input string here
var output = new StringBuilder();
foreach (var c in inputString.ToCharArray())
{
if (char.IsUpper(c))
{
output.AppendFormat("_{0}_", c);
}
else
{
output.Append(c);
}
}
This will loop through each character in the inputString if the characater is upper it inserts a _ before and after (replace that with your desired braille characters) otherwise appends the character to the output.

Categories