C# read only part of whole string [closed] - c#

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

Related

How to extract string between same char [closed]

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.

Extract the first two words from a string with C# [closed]

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 8 years ago.
Improve this question
I guys im trying to workout C# code to extract the first two words from string. below is code im doing.
public static string GetDetailsAsString(string Details)
{
string Items = //how to get first 2 word from string???
if (Items == null || Items.Length == 0)
return string.Empty;
else
return Items;
}
Define "words", if you want to get the first two words that are separated by white-spaces you can use String.Split and Enumerable.Take:
string[] words = Details.Split();
var twoWords = words.Take(2);
If you want them as separate string:
string firstWords = twoWords.First();
string secondWord = twoWords.Last();
If you want the first two words as single string you can use String.Join:
string twoWordsTogether = string.Join(" ", twoWords);
Note that this simple approach will replace new-line/tab characters with empty spaces.
Assuming the words are separated by whitespaces:
var WordsArray=Details.Split();
string Items = WordsArray[0] + ' ' + WordsArray[1];

C# - split 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 have some problems with split and check string.
I need to split string, replace halfs and check is this the same as the second string.
example: first string = tokyo second string = koyto
soo... S = a+b = b+a
S - a = b and S - b = a
a and b is part of one string (S) and may have different long in this case a = to and b = koy
first I need to check string length - is the are different - then write Error - it's easy
the I thought that I can compare strings in ASCII (case sensitivity is not important) and it' could be ok but...
I can create string tooky which have got the same size in ASCII but is not created from split and invert parts of first string...
any ideas?
static void Main(string[] args)
{
string S = "tokyo";
string T = "kyoto";
if (S.Length == T.Length)
{
split string ?
}
else
Console.WriteLine("This two words are different. No result found.");
Console.Read();
}
I would suggest doing the comparisons with strings. You can use the String.ToLower() method to convert them both to lowercase for comparison.
I am not exactly sure what problem you are trying to solve is, but from what I understand you are trying to check if string S can be split into two substrings that can be rearranged to make string T.
To check this you will want something similar to the following
for (int i = 0; i < S.length; i++) {
string back = S.substring(i);
string front = S.substring(0,i);
if (T.equals(back + front))
result = true;
}
Hope this helps
If you want to compare equality of two collections you should consider using LINQ:
static void Main(string[] args)
{
string S = "tokyo";
string T = "kyoto";
if (S.Length == T.Length)
{
if (S.Intersect(T).Any())
{
Console.WriteLine("The Contents are the same");
Console.Read();
}
}
else
Console.WriteLine("This two words are diferent. No result found.");
Console.Read();
}

How to parse number 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 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();

Extract phone number from text [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 want to build a method that will get a string (preferably the text of a textblock) and it will identify and highlight any phone numbers in the string. The goal is to enable the user to tap any number and directly call or text it(by using the appropriate launcher).
How can I work this out? Any ideas? Thank you in advance!
You can use Regular expression to do this.
Example:-
var s= new Regex(#"(\(?[0-9]{3}\)?)?\-?[0-9]{3}\-?[0-9]{4}",
RegexOptions.IgnoreCase); //North American number
var text = "Some Texxt";
MatchCollection m= s.Matches(text);
String s = "abc055667788abc";
string phoneNumber;
foreach(char c in s)
{
if(Char.isNumber(c) || c == " " || c == "+")
{
phoneNumber = phoneNumber + c;
minimumDigits++;
if(minimumDigits >= 9)
{
NumberDetected(phoneNumber);
}
}
else
{
minimumDigits = 0;
}
}
NumberDetected(string rawNumber)
{
int plusses = 0;
foreach(char c in rawNumber)
{
if(c == "+")
{
plusses++;
}
}
if(plusses <= 1)
{
if(rawNumber.StartsWith("+")
{
NumberDone(rawNumber);
}
}
else
{
MessageBox.Show("Number contained too many plusses!");
}
}

Categories