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 want to parse a number with 11 characters.
For example; number is 12345678900
With parse it should be ; 1234 5678 900
How can I do this?
Based on your example, you could use the following:
var numString = 12345678900.ToString();
var result1 = Convert.ToInt32(numString.Substring(0, 4)); //1234
var result2 = Convert.ToInt32(numString.Substring(4, 4)); //5678
var result3 = Convert.ToInt32(numString.Substring(8, 3)); //900
Something like this would probably work.
int number = 12345678900;
StringBuilder sb = new StringBuilder();
String nums = number.ToString();
char[] numsChar = nums.ToCharArray();
for(int x = 1; x < numsChar.length; x++){
if(x%4==0)
sb.Append(numsChar[x-1] + #" ");
else
sb.Append(numsChar[x-1]);
}
String parsedNumber = sb.ToString();
if you have the string with 11 chars which representing a number
so you can use something like this
string num = "12345678901";
num.ToString("0000 0000");
I am not sure but i think you want to show your number as phone number and easy to remember, so take a look at ToString method specs in MSDN
If you are talking about a string containing numeric characters then you can use this:
String.Format("{0:(####) #### ###}", 12345678900); OR
String.Format("{0:(####) #### ###}", txtPhoneNumber.text);
Assuming you mean you want the result string "1234 5678 900":
int num = 12345678900;
string numString = num.toString();
string result = String.Format("{0} {1} {2}",numString.SubString(0,4),numString.SubString(4,4),numString.SubString(8,3));
You could do:
Value.ToString("N", CultureInfo.InvariantCulture);
And then replace the dot and the comma with spaces. ;-)
long numberlong = 12345678900;
string number = numberlong.ToString();
int first = Convert.ToInt32(number.Substring(0, 4));
int second = Convert.ToInt32(number.Substring(4, 4));
int third = Convert.ToInt32(number.Substring(8, 3));
label1.Text = first.ToString() + " " + second.ToString() + " " + third.ToString();
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I have a string "ABD-DDD-RED-Large" and need to extract "DDD-RED"
using the Split I have:
var split = "ABD-DDD-RED-Large".Split('-');
var first = split[0];
var second = split[1];
var third = split[2];
var fourth = split[3];
string value = string.Join("-", second, third);
just wondering if there's a shorter code
If you just want the second and third parts of an always 4 part (delimited by -) string you can one line it with LINQ:
string value = string.Join("-", someInputString.Split('-').Skip(1).Take(2));
An input of: "ABD-DDD-RED-Large" would give you an output of: "DDD-RED"
Not enough information. You mentioned that string is not static. May be Regex?
string input = "ABD-DDD-RED-Large";
string pattern = #"(?i)^[a-z]+-([a-z]+-[a-z]+)";
string s = Regex.Match(input, pattern).Groups[1].Value;
Use regex
var match = Regex.Match(split, #".*?-(.*?-.*?)-.*?");
var value = match.Success ? match.Groups[1].Value : string.Empty;
I'm going out on a limb and assuming your string is always FOUR substrings divided by THREE hyphens. The main benefit of doing it this way is that it only requires the basic String library.
You can use:
int firstDelIndex = input.IndexOf('-');
int lastDelIndex = input.LastIndexOf('-');
int neededLength = lastDelIndex - firstDelIndex - 1;
result = input.Substring((firstDelIndex + 1), neededLength);
This is generic enough to not care what any of the actual inputs are except the hyphen character.
You may want to add a catch at the start of the method using this to ensure there are at least two hyphen's in the input string before trying to pull out the requested substring.
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 5 years ago.
Improve this question
I would like to make a feature where a string in C# can be broken into 3 word chunks like this:
Today is a nice day, and I have been driving a car /*(don't laugh lol - not a part of sentence)*/
So the first thing that I would like to do is throw out all special characters from string except for numbers and letters.
And once I do that, then goes the breaking the word into a 3 word chunk, where the output in the case of upper sentence would be:
Today is a
nice day and
I have been
driving a car
I was thinking to do this via regex, but then again there's LINQ methods and all that could solve this easily, so I'm not really sure which way to choose to choose in order to make this? What would be the most efficient way?
P.S. Also a problem that I'm thinking of is what if a word has 8 words and I want to make it into 3 chunk words...? How would I then throw out the last 2 words that don't match the criteria of forming the 3 chunk "sentence"?
Can someone help me out ?
string str = "Today is a nice day, and I have been driving a car";
str = Regex.Replace(str, "[^0-9a-zA-Z ]+", "");
string[] arr = str.Split(' ');
int nElements = 0;
for (int i = 0; i < arr.Length; i+=3)
{
if(i+3 < arr.Length)
{
nElements = 3;
}
else
{
nElements = arr.Length - i;
}
Console.WriteLine(arr.Skip(i).Take(nElements).Aggregate((current, next) => current + " " + next));
}
Get all words by using regex ([a-zA-Z]+), then put it into array and from that build 3 words chunk into a array or list.
If you have 8 words you can check if array can be divided by 3 if not just delete last two or one word. Code look like this:
string str = "Today is a nice day, and I have been driving a car";
Regex r = new Regex("[a-zA-Z]+", RegexOptions.IgnoreCase);
var wordCollection = r.Matches(str).Cast<Match>().Select(m => m.Value).ToList();
var number = wordCollection.Count % 3;
if (number == 1)
{
wordCollection.RemoveAt(wordCollection.Count - 1);
}
else if (number == 2)
{
wordCollection.RemoveAt(wordCollection.Count - 1);
wordCollection.RemoveAt(wordCollection.Count - number - 1);
}
var list = new List<string>();
for (var i = 0; i < wordCollection.Count; i+=3)
{
list.Add(string.Format("{0} {1} {2}", wordCollection[i], wordCollection[i + 1], wordCollection[i + 2]));
}
Edit:
Add howManyToRemove variable to check if i need to delete one or two words.
Edit 2:
There was a little bug in my code, I fix it.
I think here is one of the primitive ways to do that:
You should split your input string by " " which is done by using string.Split() function, which splits by white space if no argument was passed.
Now you should just pass the array you have got from split and take by 3 element.
For removing special symbols from element you can use the following RegEx pattern [^a-zA-Z0-9], where ^ - is meaning to look for any element which is not specified in [].
string a = "Today is a nice day, and I have been driving";
var res = a.Split();
List<string> groups = new List<string>();
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i=0;i< res.Length;i+=3)
{
string result = string.Empty;
try
{
result += rgx.Replace(res[i], "");
}
catch(Exception)
{
}
try
{
result +=" "+ rgx.Replace(res[i+1], ""); ;
}
catch (Exception)
{
groups.Add(result);
break;
}
try
{
result +=" "+ rgx.Replace(res[i + 2], "");
}
catch (Exception)
{
groups.Add(result);
break;
}
groups.Add(result);
}
foreach(var a1 in groups)
{
Console.WriteLine(a1);
}
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 5 years ago.
Improve this question
In asp.net, I have some values in a string as under:
1,12,123,21,23,256 and so on
I want that if i want to delete 1 then only 1 should be removed from the list, if I want to delete 12 then only number 12 should be removed from the list.
The code should be very less time taking since there will be a load of a lot of users on this button. Using string
replace() and regex , all occurances of 1 ans 12 got changed.
I tried the following:
string llist2 = "1,12,123,23,21";
string[] vals = llist2.Split(',');
int numtorem = 1;
vals = Array.FindAll(vals, val => val != numtorem).ToArray();
Here, vals is a string array so it wont work.
Then i tried int[] vals = llist2.Split(','); but llist2 is a string, so it wont convert. If I add on more code for conversions, then code execution will be too much and page will become slow due to a lot of users working in parallel.
NOTE: the string in the llist2 is coming from the database using a select query. I hope I will not be asked to share the select query code too.
I think, it's better to convert 1 number (the one to be removed), then the whole list.
update your code to convert the number to string and that's it
string llist2 = "1,12,123,23,21";
string[] vals = llist2.Split(',');
int numtorem = 1;
llist2 = String.Join(",", Array.FindAll(vals, val => val != numtorem.ToString()));
Don't Worry Bro, people here are in habit of down voting the posts quickly rather than helping:
Here is the solution for you:
string llist2 = "1,12,123,23,21";
int[] vals = Array.ConvertAll(llist2.Split(','), int.Parse);
int numtorem = 1;
vals = Array.FindAll(vals, val => val != numtorem).ToArray();
Hope this helps.
You can split directly to List<int> and remove the number.
List<int> vals = llist2.Split(',').Select(Int32.Parse).ToList();
vals.Remove(numtorem);
If yout don't want convert the list to integers, you can do the #ASh solution, or this:
string llist2 = "1,12,123,23,21";
int numtorem = 1;
llist2 = Regex.Replace(llist2, string.Format("^{0},|,{0}(,)|,{0}$", numtorem), "$1");
//"$1" is the first match group: (,) => string.Empty or ","
//Works fine with 1, 123, 21, etc...
//Console.WriteLine(llist2);
//Output 12,123,23,21
Like this
string llist2 = "1,12,123,23,21,1";
string[] vals = llist2.Split(',');
int numtorem = 1;
string[] results = Array.FindAll(vals, s => !s.Equals(Convert.ToString(numtorem))).ToArray();
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
How to format my text in TextBox?
My text value is:
00010001008002020100010000530997000014820000148200010000012C00001482000014820000148200010000012C000014820000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000101000000000000000000000000000000000000003F
And I want my output to be like this:
00010001-0080-02020100010000-53099700-00148200-00-14820001-0000-012C0000-14820000-1482000-0148-20001000-0012C000-0148-20000000-00000000-0000-00-000000000-00000000-0000-00000000-0000000-0000-00000000-00000000-00000000-0000-00000000-00-00000-000001010-00000000-000000000-0000-000000000-00000003-F
Your format must be fixed. It should not be dynamic.
I am just providing a logic you could append the further detail in regex string.
string mystring = "000100010080"
string regex = #"(\w{4})(\w{4})(\w{4})";
string strValue = Regex.Replace(mystring, regex, #"$1-$2-$3");
OUTPUT:
0001-0001-0080
EDITED: Take a look at complete example
string[] patern = "XXXXXXXX-XXXX-XXXXXXXXXXXXXX-XXXXXXXX-XXXXXXXX-XX-XXXXXXXX-
XXXX-XXXXXXXX-XXXXXXXX-XXXXXXX-XXXX-XXXXXXXX-XXXXXXXX-XXXX-
XXXXXXXX-XXXXXXXX-XXXX-XX-XXXXXXXXX-XXXXXXXX-XXXX-XXXXXXXX-
XXXXXXX-XXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXX-XXXXXXXX-XX-
XXXXX-XXXXXXXXX-XXXXXXXX-XXXXXXXXX-XXXX-XXXXXXXXX-XXXXXXXX-
X".Split('-');
string mystring = "00010001008002020100010000530997000014820000148200010000012C0
0001482000014820000148200010000012C00001482000000000000000000
0000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000001010000000000000000000000000000
00000000003F";
string regex = string.Empty;
string match = string.Empty;
for(int i=0; i<patern.Length;i++)
{
regex += #"(\w{" + patern[i].Length + "})";
match += "$" + (i + 1).ToString() + "-";
}
match = match.Substring(0, match.Length - 1);
txtMyTextBox.Text = Regex.Replace(mystring, regex, match);
Assuming that you have a fixed pattern of inserting hyphens and the string length is same every time, then you could do something like this:
int[] indices = new int[] { 2, 5, 11 };
string yourLongString = "blahblahblah";
foreach( var index in indices.Reverse() )
{
yourLongString = yourLongString.Insert( index - 1, "-" );
}
OR
Assuming you have no predefined pattern, you could insert hyphens anywhere and hence still you could use the same code above with the tweak to randomize the indices array, if needed.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have a string which has a following format:
"####/xxxxx"
The text before the "/" is always an integer and I need to read it. How do I get only the integer part of this string (before the "/")?
Thank you for your help.
You can split the string on / and then use int.TryParse on the first element of array to see if it is an integer like:
string str = "1234/xxxxx";
string[] array = str.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);
int number = 0;
if (str.Length == 2 && int.TryParse(array[0], out number))
{
//parsing successful.
}
else
{
//invalid number / string
}
Console.WriteLine(number);
Use IndexOf and Substring:
int indexOfSlash = text.IndexOf('/');
string beforeSlash = null;
int numBeforeSlash = int.MinValue;
if(indexOfSlash >= 0)
{
beforeSlash = text.Substring(0, indexOfSlash);
if(int.TryParse(beforeSlash, out numBeforeSlash))
{
// numBeforeSlash contains the real number
}
}
Another alternative: use a regular expression:
var re = new System.Text.RegularExpression(#"^(\d+)/", RegexOptions.Compiled);
// ideally make re a static member so it only has to be compiled once
var m = re.Match(text);
if (m.IsMatch) {
var beforeSlash = Integer.Parse(re.Groups[0].Value);
}