find and extract a number from a string C# [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 3 years ago.
Improve this question
I have a requirement to find and extract a number contained within a string.
For example, from these strings:
"O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000"
extract :
1.2275000
2.3060000
3.3260000
....

It would be :
string temp = yourText;
List<int> numbers = new List<int>();
Regex re = new Regex(#"\d+");
Match m = re.Match(temp);
while (m.Success)
{
numbers.Add(Convert.ToInt32(m.Value));
temp = temp.Substring(m.Index + m.Length);
m = re.Match(temp);
}

First of all, you mentioned "from these strings", though you gave a single string. I am not clear about this part.
Secondly, what do you mean by extract? Do you want to find the position of a number in the string? If yes then you can simply use string search as following
string str = "O:2275000 BF:3060000 D:3260000";
int index = str.IndexOf("3060000");
if (index != -1)
{
Console.WriteLine(index);
}
else
{
Console.WriteLine("Not Found");
}
Or if the problem is stated like that: you were given a string and you want to extract the numbers out of it, then you can do it like so:
List<decimal> findNumbers(string str)
{
List<decimal> x = new List<decimal>();
string tokens = "";
foreach (char ch in str)
{
if (Char.IsNumber(ch))
{
tokens = tokens + ch;
}
if (!Char.IsNumber(ch) && !String.IsNullOrEmpty(tokens))
{
decimal num = Convert.ToDecimal(tokens);
x.Add(Convert.ToDecimal(num));
tokens = "";
}
}
if (String.IsNullOrEmpty(tokens))
{
x.Add(Convert.ToDecimal(tokens));
}
return x;
}
this function returns the list of numbers available in the string.

We can try using string split here:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
foreach (string n in numbers)
{
Console.WriteLine(n);
}
This prints:
2275000
3060000
3260000

You can do this in a single line with Linq.
string numbers = "O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000";
List<int> list = numbers.Split(' ').Select(x => Convert.ToInt32(string.Concat(x.Where(Char.IsDigit)))).ToList();

Tim Biegeleisen's answer is correct except it does not produce floating point output as you mentioned in your question. In his answere, just replace foreach loop with for statement, like this:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("{0}.{1}", i+1, numbers[i]);
}

Related

How to get all string "possibilities" [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 2 years ago.
Improve this question
Given a string like string s = "a(b)cd(ef)",
what is the best way to get a list/array containing all the following strings:
"acd",
"abcd",
"acdef",
"abcdef"
Additional information:
The order of the result doesn't matter.
The amount of parenthesis is unknown
I have tried to do this with RegEx, but didn't get very far.
There are many ways to do this, however here is an example using a mask array to keep track of the permutation state, some regex, and a few helper methods
Given
// work out the states of the combination
public static bool GetNextState(bool[] states)
{
for (var i = 0; i < states.Length; i++)
if ((states[i] = !states[i]) == true)
return false;
return true;
}
// Create the combination
public static string Join(string[] split, string[] matches, bool[] states)
{
var sb = new StringBuilder();
for (var i = 0; i < states.Length; i++)
sb.Append(split[i] + (states[i]? matches[i]:""));
sb.Append(split.Last());
return sb.ToString();
}
// enumerate the results
public static IEnumerable<string> Results(string input)
{
var matches = Regex.Matches(input, #"\(.+?\)")
.Select(x => x.Value.Trim('(', ')'))
.ToArray();
var split = Regex.Split(input, #"\(.+?\)");
var states = new bool[matches.Length];
do {
yield return Join(split, matches, states);
} while (!GetNextState(states));
}
Usage
string s = "a(b)cd(ef)";
foreach (var result in Results(s))
Console.WriteLine(result);
Output
acd
abcd
acdef
abcdef
Full Demo Here
Michael Randall's answer is correct, but after some more thinking I was finally able to come up with a (probably not very good) working solution as well
string s = "a(b)cd(ef)";
List<string> result = new List<string>();
int amount = s.Split('(').Length;
amount = (int)Math.Pow(2, amount - 1);
for (int i = 0; i < amount; i++)
{
string temp = string.Copy(s);
string binaryString = Convert.ToString(i, 2).PadLeft(amount, '0');
string tempResult = "";
for (int j = 0; j < binaryString.Length && !temp.Equals(""); j++)
{
Regex regex = new Regex(#"[^(]*");
tempResult += regex.Match(temp).Value;
if (binaryString[binaryString.Length - 1 - j].Equals('1'))
{
string regexStr = #"\(([^)]*)\)";
regex = new Regex(regexStr);
tempResult += regex.Match(temp).Value;
}
if (temp.Contains(')'))
temp = temp.Substring(temp.IndexOf(')') + 1);
else temp = "";
}
result.Add(tempResult.Replace("(", "").Replace(")", ""));
}

Why parsing string of path name is not working? [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 this code:
List<string> dirParts = new List<string>();
int index = 0;
for (int i = 0; i < dirName.Length; i++)
{
index = dirName.IndexOf("/");
string dironly = dirName.Substring(index, dirName.Length - index);
dirParts.Add(dironly);
}
dirName for example contains d/1/2/3/4/5
So I need that in the List dirParts in the end I will have in index 0 d, in index 1 d/1, in index 2 d/1/2, in index 3 d/1/2/3, in index 4 d/1/2/3/4, in index 5 d/1/2/3/4/5
So when I look on the List it should look like this:
d
d/1
d/1/2
d/1/2/3
d/1/2/3/4
d/1/2/3/4/5
Possible implementation:
List<string> dirParts = new List<string>();
int index = -1;
while (true) {
index = dirName.IndexOf("/", index + 1);
if (index < 0) {
dirParts.Add(dirName);
break;
}
else
dirParts.Add(dirName.Substring(0, index));
}
Apart from the fact that this kind of path manipulation is best left to the library, lest your code breaks on strange exceptional directory names, your code works as it does because you look everytime for the same "/".
You should search after the last one:
index = dirName.IndexOf("/", index+1);
If you really want to do it that way:
for (int i = 0; i < dirName.Length; i++) {
index = dirName.IndexOf("/", index);
if (index == -1)
i = index = dirName.Length; //last one
dirParts.Add(dirName.Substring(0, index++));
}
If it's a directory, I like to use Path library personally. The only issue would be the use of / over \ in directory name, so you'd have to call .Replace before inserting:
var orig = "d/1/2/3/4/5"; // Original string
List<String> dirParts = new List<String>(new[]{ orig }); // start out with list of original
// Get the directory below this one. (drop off last folder)
String part = Path.GetDirectoryName(orig);
while (!String.IsNullOrEmpty(part))
{
// add it to the first entry in the list
dirParts.Insert(0, part.Replace('\\','/'));
// get the next parent folder.
part = Path.GetDirectoryName(part);
}
/* dirParts = [ "d", "d/1", "d/1/2", ... ] */
However, if you're just looking for the down and dirty LINQ approach:
var orig = "d/1/2/3/4/5";
String[] parts = orig.Split('/');
var dirParts = Enumerable.Range(1, parts.Length)
.Select (e => String.Join("/", parts.Take(e)));

Splitting string into an array on 16th char [duplicate]

This question already has answers here:
Splitting a string into chunks of a certain size
(39 answers)
Split string after certain character count
(4 answers)
Closed 8 years ago.
I have a text file with various 16 char strings both appended to one another and on separate lines. I've done this
FileInfo f = new FileInfo("d:\\test.txt");
string FilePath = ("d:\\test.txt");
string FileText = new System.IO.StreamReader(FilePath).ReadToEnd().Replace("\r\n", "");
CharCount = FileText.Length;
To remove all of the new lines and create one massively appended string. I need now to split this massive string into an array. I need to split it up on the consecutive 16th char until the end. Can anyone guide me in the right direction? I've taken a look at various methods in String such as Split and in StreamReader but am confused as to what the best way to go about it would be. I'm sure it's simple but I can't figure it out.
Thank you.
Adapting the answer from here:
You could try something like so:
string longstr = "thisisaverylongstringveryveryveryveryverythisisaverylongstringveryveryveryveryvery";
IEnumerable<string> splitString = Regex.Split(longstr, "(.{16})").Where(s => s != String.Empty);
foreach (string str in splitString)
{
System.Console.WriteLine(str);
}
Yields:
thisisaverylongs
tringveryveryver
yveryverythisisa
verylongstringve
ryveryveryveryve
ry
One possible solution could look like this (extracted as extension method and made dynamic, in case different token size is needed and no hard-coded dependencies):
public static class ProjectExtensions
{
public static String[] Chunkify(this String input, int chunkSize = 16)
{
// result
var output = new List<String>();
// temp helper
var chunk = String.Empty;
long counter = 0;
// tokenize to 16 chars
input.ToCharArray().ToList().ForEach(ch =>
{
counter++;
chunk += ch;
if ((counter % chunkSize) == 0)
{
output.Add(chunk);
chunk = String.Empty;
}
});
// add the rest
output.Add(chunk);
return output.ToArray();
}
}
The standard usage (16 chars) looks like this:
// 3 inputs x 16 characters and 1 x 10 characters
var input = #"1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890";
foreach (var chunk in input.Chunkify())
{
Console.WriteLine(chunk);
}
The output is:
1234567890ABCDEF
1234567890ABCDEF
1234567890ABCDEF
1234567890
Usage with different token size:
foreach (var chunk in input.Chunkify(13))
{
Console.WriteLine(chunk);
}
and the corresponding output:
1234567890ABC
DEF1234567890
ABCDEF1234567
890ABCDEF1234
567890
It is not a fancy solution (and could propably be optimised for speed), but it works and it is easy to understand and implement.
Create a list to hold your tokens. Then get subsequent substrings of length 16 and add them to the list.
List<string> tokens = new List<string>();
for(int i=0; i+16<=FileText.Length; i+=16) {
tokens.Add(FileText.Substring(i,16));
}
As mentioned in the comments, this ignores the last token if it has less than 16 characters. If you want it anyway you can write:
List<string> tokens = new List<string>();
for(int i=0; i<FileText.Length; i+=16) {
int len = Math.Min(16, FileText.Length-i));
tokens.Add(FileText.Substring(i,len);
}
Please try this method. I haven't tried it , but used it once.
int CharCount = FileText.Length;
int arrayhold = (CharCount/16)+2;
int count=0;
string[] array = new string[arrayhold];
for(int i=0; i<FileText.Length; i+=16)
{
int currentleft = FileText.Length-(16*count);
if(currentleft>16)
{
array[count]=FileText.Substring(i,16);
}
if(currentleft<16)
{
array[count]=FileText.Substring(i,currentleft);
}
count++;
}
This is the new code and provide a TRUE leftovers handling. Tested in ideone
Hope it works
Try this one:
var testArray = "sdfsdfjshdfalkjsdfhalsdkfjhalsdkfjhasldkjfhasldkfjhasdflkjhasdlfkjhasdlfkjhasdlfkjhasldfkjhalsjfdkhklahjsf";
var i = 0;
var query = from s in testArray
let num = i++
group s by num / 16 into g
select new {Value = new string(g.ToArray())};
var result = query.Select(x => x.Value).ToList();
result is List containing all the 16 char strings.

Take the first characters [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 this String: Hello to all. I want to take first 2 charcters from each word. The result: Hetoal. How can I do? I tried with a foreach
foreach( string str in String)
but I received an error: Cannot convert type char to String
You will need to split the sentence string into words, like this:
var sentence = "Hello to all.";
var words = sentence.Split(' ');
Then you can loop through each of the words in the sentence and grab the first two characters of each and append them to a result, like this:
string result;
var resultBuilder = new StringBuilder();
foreach(string word in words)
{
// Get the first two characters if word has two characters
if (word.Length >= 2)
{
resultBuilder.Append(word.Substring(0, 2));
}
else
{
// Append the whole word, because there are not two first characters to get
resultBuilder.Append(word);
}
}
result = resultBuilder.ToString();
Code example :
string someString = "Hello to all";
string[] words = someString.Split(' ');
string finalString = "";
foreach (string word in words) {
finalString += word.Substring(0, 2);
}
// finalString = "Hetoal";
This splits the string into words and then foreach word it finds the first 2 characters and appends them to the finalString object.
One possible solution can be
string str = "Hello to all.";
StringBuilder output = new StringBuilder();
foreach (string s in str.Split(' '))
{
output.Append(s.Take(2));
}
string result = output.ToString();
string myString = "Hello to all";
var result = myString
.Split(' ')
.Select(x => x.Substring(0,Math.Min(x.Length,2)))
.Aggregate((y,z) => y + z);
You can do this
split your string around space
string[] words = s.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word.Substring(0,2));
}
Some linq here:
string s = "Hello to all";
var words = s.Split(' ');
var result = new string(words.SelectMany(w=>w.Take(2)).ToArray());
String str = "Hello to all";
String[] words = str.Split(' ');
String completeWord = "";
foreach (String word in words)
{
if(word.Length>1)
completeWord+=word.Substring(0, 2);
}
//original message
string message = "hello to all";
//split into a string array using the space
var messageParts = message.Split(' ');
//The SelectMany here will select the first 2 characters of each
// array item. The String.Join will then concat them with an empty string ""
var result = String.Join("",messageParts.SelectMany(f=>f.Take(2)));
string word = "Hellow to all";
string result = "";
foreach(var item in word.Take(2))
{
result += item;
}
string str = "Hello to all";
string result = str.Split().Select(word => word.Substring(0, 2)).Aggregate((aggr, next) => aggr + next);

C# Replace string by position [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to replace a comma in a string.
For example, the data is the currency value of a part.
Eg. 453,27 This is the value I get from an SAP database
I need to replace the comma to a period to fix the value to the correct amount. Now sometimes, it will be in the thousands.
Eg. 2,356,34 This value needs to be 2,356.34
So, I need help manipulating the string to replace comma that is 2 characters from the end.
Thanks for the help
string a = "2,356,34";
int pos = a.LastIndexOf(',');
string b = a.Substring(0, pos) + "." + a.Substring(pos+1);
You'll need to add a bit of checking for cases where there are no commas in the string, etc. but that's the core code.
You could also do it with a regex, but this is simple and reasonably efficient.
A quick google search gave me this:
void replaceCharWithChar(ref string text, int index, char charToUse)
{
char[] tmpBuffer = text.ToCharArray();
buffer[index] = charToUse;
text = new string(tmpBuffer);
}
So your "charToUse" should be '.'. If it always is 2 characters from end, your index should be
text.length - 3.
http://www.dreamincode.net/code/snippet1843.htm
If I understand correctly, you always need to replace the last comma with a period.
public string FixSAPNumber(string number)
{
var str = new StringBuilder(number);
str[number.LastIndexOf(',')] = '.';
return str.ToString();
}
string item_to_replace = "234,45";
var item = decimal.Parse(item_to_replace);
var new_item = item/100;
//if you need new_item as string
//then new_item.ToString(Format)
Use this :
string str = "2,356,34";
string[] newStr = str.Split(',');
str = string.Empty;
for (int i = 0; i <= newStr.Length-1; i++)
{
if (i == newStr.Length-1)
{
str += "."+newStr[i].ToString();
}
else if (i == 0)
{
str += newStr[i].ToString();
}
else
{
str += "," + newStr[i].ToString();
}
}
string s = str;
string x = "2,356,34";
if (x[x.Length - 3] == ',')
{
x = x.Remove(x.Length - 3, 1);
x = x.Insert(x.Length - 2, ".");
}

Categories

Resources