Getting two numbers which are separated by colon [closed] - c#

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

Related

how to retrieve all integers from parts of a string? [duplicate]

This question already has answers here:
Extract multiple integers from string and store as int
(3 answers)
Closed 2 years ago.
What is the most effective and efficient way to retrieve integers from a string?
For example, my input string is "1s 2ss 5rt" and I only want "1 2 5"
I am using C# and .NET framework
I found it in 1 google search "c# regex get digits from string" https://www.dotnetperls.com/regex-split-numbers
This is the most effective way:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
const string input = "There are 4 numbers in this string: 40, 30, and 10.";
// Split on one or more non-digit characters.
string[] numbers = Regex.Split(input, #"\D+");
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
Console.WriteLine("Number: {0}", i);
}
}
}
}
Output
Number: 4
Number: 40
Number: 30
Number: 10
RegEx's are quite expensive so the most efficient way is a for loop and IsDigit (but there's a couple of Thai characters that sneak through the IsDigit check).
String s = "1s 2ss 5rt";
List<int> digitsInString = new List<int>();
foreach (char c in s)
{
if (Char.IsDigit(c)) digitsInString.Add(Convert.ToInt32(c));
}

Find Substring at Index then retrieve number following [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have this string value
The Quick Brown Fox VOL 5 Jumped Over 10 Fences'
I need to find the next number immediately after some input, like "VOL". There will be a space between my input and the number.
In this example, I need to return 5. If I passed in "Over" I would get 10.
How do I do that?
Regex is a great tool for this sort of thing. The specific regex you use can depend on things like whether VOL always has a space before it, whether "numbers" can have commas or decimals, etc., but this can give you an idea:
IEnumerable<string> volValues = Regex.Matches("The Quick Brown Fox VOL 5 Jumped Over 10 Fences", #"VOL\s*(\d+)")
.Cast<Match>()
.Select(m => m.Groups[1].Value);
If you want to be able to change the preceding value (e.g. "VOL"), you can abstract that out, but be sure to escape it for correctness. That might look something like this:
var precedingText = "VOL";
var input = "The Quick Brown Fox VOL 5 Jumped Over 10 Fences";
List<int> integersAfterPrecedingText = Regex.Matches(input, #$"{Regex.Escape(precedingText)}\s+(\d+)")
.Cast<Match>()
.Select(m => m.Groups[1].Value)
.Select(int.Parse)
.ToList();
Try:
string pattern = #"(?<=VOL *)\d+";
string input = "The Quick Brown Fox VOL 533 Jumped Over 10 Fences";
Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
if (m.Success)
Console.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index);
Note: .Net Regex supports look behind with non fixed width.
There are numerous ways to do it, but here are some simple ways to do it (without Regex).
First Approach
public static int GetValue(string text, string keyword)
{
var find = text.Substring(text.IndexOf(keyword) + keyword.Length);
string _tempValue = string.Empty;
for (int x = 0; x < find.Length; x++)
{
if (!char.IsDigit(find[x]) && x > 0)
break;
_tempValue += find[x];
}
if (int.TryParse(_tempValue.Trim(), out int number))
{
return number;
}
else
{
return 0;
}
}
Second Approach
public static int GetValue(string text, string keyword)
{
var list = text.Split(' ').ToList();
for (int x = 0; x < list.Count; x++)
{
if (list[x].Equals(keyword))
{
if (int.TryParse(list[x + 1], out int number))
{
return number;
}
else
{
break;
}
}
}
return 0;
}
usage :
var number = GetValue("The Quick Brown Fox VOL 5 Jumped Over 10 Fences", "VOL");
The first approach will first get the index of the desired keyword, then it'll slice the first portion of the string, so using your example, if we use the keyword VOL on
The Quick Brown Fox VOL 5 Jumped Over 10 Fences'
it'll slice it to :
5 Jumped Over 10 Fences
then we use this part in a loop, to get the numbers, and the loop will break at the first character that is not a number (like space, letters ..etc).
The second approach similar idea, but it converts the string to list and splits it by spaces. So, each word will be stored separately. So, if VOL index = 4, then the next index (5) will store the number.
int.TryParse used for insurance to always get an int.
I tried to give you something to start with. The examples needs some work though, but it's just for demonstration purposes.

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

Get values between string in C# [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
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);
}

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