Right of a character in C# - c#

How do I get right(string) in C#?
if user="MyDomain\jKing"
I want just jking from the above string.
int index;
string user;
index = User.Identity.Name.IndexOf("\\");
user = (index > 0 ? User.Identity.Name.Substring(0, index) : "");

string user = User.Identity.Name
user= user.Remove(0, user.IndexOf(#"\")+ 1);

var user = User.Identity.Name;
var index = user.IndexOf("\\");
if (index < 0 || index == user.Length - 1)
{
user = string.Empty;
}
else
{
user = user.Substring(index + 1);
}

User.Identity.Name.Split(#"\")[1]

Might as well make it re-usable. Here are some extension methods patterned after the XLST functions substring-before and substring-after to make it generic.
Usage: var userNm = (User.Identity.Name.Contains(#"\") ? User.Identity.Name.SubstringAfter(#"\") : User.Identity.Name);
public static class StringExt {
public static string SubstringAfter(this string s, string searchString) {
if (String.IsNullOrEmpty(searchString)) return s;
var idx = s.IndexOf(searchString);
return (idx < 0 ? "" : s.Substring(idx + searchString.Length));
}
public static string SubstringBefore(this string s, string searchString) {
if (String.IsNullOrEmpty(searchString)) return s;
var idx = s.IndexOf(searchString);
return (idx < 0 ? "" : s.Substring(0, idx));
}
}

Related

Remove duplicates from a string

Say I have a string like this:
anxxnbddc
I want to process this and return a string which contains only the characters which appear in the input string exactly once. Therefore my expected output would be:
abc
I have tried this code:
static string RemoveDuplicates(string key)
{
string result = "";
for (int i = 0; i < key.Length - 1; i++)
{
if (key[i] != key[i + 1])
{
result += key[i];
}
}
return result;
}
but my output is:
anxnbd
How do I get my desired output?
string noDuplicates = new string(input.ToCharArray().Where(c => input.ToCharArray().FindAll(x => x == c).Length == 1).ToArray());
Do this with Linq approach:
string withoutDuplicates= new string(yourString.ToCharArray().Distinct().ToArray());
Must help

c# console application program for palindrome string

public static int isPalindrome(char[] String)
{
if (String.Length == 0 || String.Length == 1)
return 1;
if (String[0] != String[String.Length - 1])
return 0;
return Convert.ToUInt32(isPalindrome(String);
}
I am not able to make it as instance method i am getting problems so please help me how to make it as dynamic
This should work:
public static int isPalindrome(char[] String)
{
string smallerString = String.ToString().Substring(1, String.Length - 1);
if (String.Length == 0 || String.Length == 1)
return 1;
if (String[0] != String[String.Length - 1])
return 0;
return Convert.ToInt32(isPalindrome(smallerString.ToCharArray()));
}
Without changing your types and return values
public static int isPalindrome(char[] str)
{
if (str.Length == 0 || str.Length == 1)
return 1;
if (str[0] != str[str.Length - 1])
return 0;
return isPalindrome(str.Skip(1).Take(str.Length-2).ToArray());
}
You are passing the same value to isPalindrome again and again. You can try something like the following (note I've used string in the example below):
private static bool isPalindrome(string s)
{
if(s.Length == 1 || s.Length == 0)
return true;
if(s[0] != s[s.Length -1])
return false;
return isPalindrome(s.SubsString(1, s.Length -2));
}
I think it could be very easy implemented.
public static bool IsPalindrome(String text)
{
if(string.IsNullOrWhiteSpace(text))
return false;
char[] arr = text.ToCharArray();
Array.Reverse(arr);
var reversedText = new string(arr);
return string.Equals(text, reversedText, StringComparison.OrdinalIgnoreCase);
}

Auto Generate alphanumeric Unique Id with C#

Total string length is 5 chars
I have a scenario, ID starts with
A0001 and ends with A9999 then
B0001 to B9999 until F0001 to f9999
after that
FA001 to FA999 then
FB001 to FB999 until ....FFFF9
Please suggest any idea on how to create this format.
public static IEnumerable<string> Numbers()
{
return Enumerable.Range(0xA0000, 0xFFFF9 - 0xA0000 + 1)
.Select(x => x.ToString("X"));
}
You could also have an id generator class:
public class IdGenerator
{
private const int Min = 0xA0000;
private const int Max = 0xFFFF9;
private int _value = Min - 1;
public string NextId()
{
if (_value < Max)
{
_value++;
}
else
{
_value = Min;
}
return _value.ToString("X");
}
}
I am a few years late. But I hope my answer will help everyone looking for a good ID Generator. None of the previous answers work as expected and do not answer this question.
My answer fits the requirements perfectly. And more!!!
Notice that setting the _fixedLength to ZERO will create dynamically sized ID's.
Setting it to anything else will create FIXED LENGTH ID's;
Notice also that calling the overload that takes a current ID will "seed" the class and consecutive calls DO NOT need to be called with another ID. Unless you had random ID's and need the next one on each.
Enjoy!
public static class IDGenerator
{
private static readonly char _minChar = 'A';
private static readonly char _maxChar = 'C';
private static readonly int _minDigit = 1;
private static readonly int _maxDigit = 5;
private static int _fixedLength = 5;//zero means variable length
private static int _currentDigit = 1;
private static string _currentBase = "A";
public static string NextID()
{
if(_currentBase[_currentBase.Length - 1] <= _maxChar)
{
if(_currentDigit <= _maxDigit)
{
var result = string.Empty;
if(_fixedLength > 0)
{
var prefixZeroCount = _fixedLength - _currentBase.Length;
if(prefixZeroCount < _currentDigit.ToString().Length)
throw new InvalidOperationException("The maximum length possible has been exeeded.");
result = result = _currentBase + _currentDigit.ToString("D" + prefixZeroCount.ToString());
}
else
{
result = _currentBase + _currentDigit.ToString();
}
_currentDigit++;
return result;
}
else
{
_currentDigit = _minDigit;
if(_currentBase[_currentBase.Length - 1] == _maxChar)
{
_currentBase = _currentBase.Remove(_currentBase.Length - 1) + _minChar;
_currentBase += _minChar.ToString();
}
else
{
var newChar = _currentBase[_currentBase.Length - 1];
newChar++;
_currentBase = _currentBase.Remove(_currentBase.Length - 1) + newChar.ToString();
}
return NextID();
}
}
else
{
_currentDigit = _minDigit;
_currentBase += _minChar.ToString();
return NextID();
}
}
public static string NextID(string currentId)
{
if(string.IsNullOrWhiteSpace(currentId))
return NextID();
var charCount = currentId.Length;
var indexFound = -1;
for(int i = 0; i < charCount; i++)
{
if(!char.IsNumber(currentId[i]))
continue;
indexFound = i;
break;
}
if(indexFound > -1)
{
_currentBase = currentId.Substring(0, indexFound);
_currentDigit = int.Parse(currentId.Substring(indexFound)) + 1;
}
return NextID();
}
}
This is a sample of the ouput using _fixedLength = 4 and _maxDigit = 5
A001
A002
A003
A004
A005
B001
B002
B003
B004
B005
C001
C002
C003
C004
C005
AA01
AA02
AA03
AA04
AA05
AB01
AB02
AB03
AB04
AB05
AC01
AC02
AC03
AC04
AC05
see this code
private void button1_Click(object sender, EventArgs e)
{
string get = label1.Text.Substring(7); //label1.text=ATHCUS-100
MessageBox.Show(get);
string ou="ATHCUS-"+(Convert.ToInt32(get)+1).ToString();
label1.Text = ou.ToString();
}
Run this query in order to get the last ID in the database
SELECT TOP 1 [ID_COLUMN] FROM [NAME_OF_TABLE] ORDER BY [ID_COLUMN] DESC
Read the result to a variable and then run the following function on the result in order to get the next ID.
public string NextID(string lastID)
{
var allLetters = new string[] {"A", "B", "C", "D", "E", "F"};
var lastLetter = lastID.Substring(0, 1);
var lastNumber = int.Parse(lastID.Substring(1));
if (Array.IndexOf(allLetters, lastLetter) < allLetters.Length - 1 &&
lastNumber == 9999)
{
//increase the letter
lastLetter = allLetters(Array.IndexOf(allLetters, lastLetter) + 1);
lastNumber = 0;
} else {
lastLetter = "!";
}
var result = lastLetter + (lastNumber + 1).ToString("0000");
//ensure we haven't exceeded the upper limit
if (result.SubString(0, 1) == "!") {
result = "Upper Bounds Exceeded!";
}
return result;
}
DISCLAIMER
This code will only generate the first set of IDs. I do not understand the process of generating the second set.
If you need to take it from the database and do this you can use something like the following.
int dbid = /* get id from db */
string id = dbid.ToString("X5");
This should give you the format you are looking for as a direct convert from the DB ID.

How to separate character and number part from string

E.g., I would like to separate:
OS234 to OS and 234
AA4230 to AA and 4230
I have used following trivial solution, but I am quite sure that there should be a more efficient and robust solution .
private void demo()
{ string cell="ABCD4321";
int a = getIndexofNumber(cell);
string Numberpart = cell.Substring(a, cell.Length - a);
row = Convert.ToInt32(rowpart);
string Stringpart = cell.Substring(0, a);
}
private int getIndexofNumber(string cell)
{
int a = -1, indexofNum = 10000;
a = cell.IndexOf("0"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("1"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("2"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("3"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("4"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("5"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("6"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("7"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("8"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("9"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
if (indexofNum != 10000)
{ return indexofNum; }
else
{ return 0; }
}
Regular Expressions are best suited for this kind of work:
using System.Text.RegularExpressions;
Regex re = new Regex(#"([a-zA-Z]+)(\d+)");
Match result = re.Match(input);
string alphaPart = result.Groups[1].Value;
string numberPart = result.Groups[2].Value;
Use Linq to do this
string str = "OS234";
var digits = from c in str
select c
where Char.IsDigit(c);
var alphas = from c in str
select c
where !Char.IsDigit(c);
Everyone and their mother will give you a solution using regex, so here's one that is not:
// s is string of form ([A-Za-z])*([0-9])* ; char added
int index = s.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
string chars = s.Substring(0, index);
int num = Int32.Parse(s.Substring(index));
I really like jason's answer. Lets improve it a bit. We dont need regex here. My solution handle input like "H1N1":
public static IEnumerable<string> SplitAlpha(string input)
{
var words = new List<string> { string.Empty };
for (var i = 0; i < input.Length; i++)
{
words[words.Count-1] += input[i];
if (i + 1 < input.Length && char.IsLetter(input[i]) != char.IsLetter(input[i + 1]))
{
words.Add(string.Empty);
}
}
return words;
}
This solution is linear O(n).
output
"H1N1" -> ["H", "1", "N", "1"]
"H" -> ["H"]
"GH1N12" -> ["GH", "1", "N", "12"]
"OS234" -> ["OS", "234"]
Same solution with a StringBuilder
public static IEnumerable<string> SplitAlpha(string input)
{
var words = new List<StringBuilder>{new StringBuilder()};
for (var i = 0; i < input.Length; i++)
{
words[words.Count - 1].Append(input[i]);
if (i + 1 < input.Length && char.IsLetter(input[i]) != char.IsLetter(input[i + 1]))
{
words.Add(new StringBuilder());
}
}
return words.Select(x => x.ToString());
}
Try it Online!
If you want resolve more occurrences of char followed by number or vice versa you can use
private string SplitCharsAndNums(string text)
{
var sb = new StringBuilder();
for (var i = 0; i < text.Length - 1; i++)
{
if ((char.IsLetter(text[i]) && char.IsDigit(text[i+1])) ||
(char.IsDigit(text[i]) && char.IsLetter(text[i+1])))
{
sb.Append(text[i]);
sb.Append(" ");
}
else
{
sb.Append(text[i]);
}
}
sb.Append(text[text.Length-1]);
return sb.ToString();
}
And then
var text = SplitCharsAndNums("asd1 asas4gr5 6ssfd");
var tokens = text.Split(' ');
Are you doing this for sorting purposes? If so, keep in mind that Regex can kill performance for large lists. I frequently use an AlphanumComparer that's a general solution to this problem (can handle any sequence of letters and numbers in any order). I believe that I adapted it from this page.
Even if you're not sorting on it, using the character-by-character approach (if you have variable lengths) or simple substring/parse (if they're fixed) will be a lot more efficient and easier to test than a Regex.
I have used bniwredyc's answer to get Improved version of my routine:
private void demo()
{
string cell = "ABCD4321";
int row, a = getIndexofNumber(cell);
string Numberpart = cell.Substring(a, cell.Length - a);
row = Convert.ToInt32(Numberpart);
string Stringpart = cell.Substring(0, a);
}
private int getIndexofNumber(string cell)
{
int indexofNum=-1;
foreach (char c in cell)
{
indexofNum++;
if (Char.IsDigit(c))
{
return indexofNum;
}
}
return indexofNum;
}
.NET 2.0 compatible, without regex
public class Result
{
private string _StringPart;
public string StringPart
{
get { return _StringPart; }
}
private int _IntPart;
public int IntPart
{
get { return _IntPart; }
}
public Result(string stringPart, int intPart)
{
_StringPart = stringPart;
_IntPart = intPart;
}
}
class Program
{
public static Result GetResult(string source)
{
string stringPart = String.Empty;
int intPart;
var buffer = new StringBuilder();
foreach (char c in source)
{
if (Char.IsDigit(c))
{
if (stringPart == String.Empty)
{
stringPart = buffer.ToString();
buffer.Remove(0, buffer.Length);
}
}
buffer.Append(c);
}
if (!int.TryParse(buffer.ToString(), out intPart))
{
return null;
}
return new Result(stringPart, intPart);
}
static void Main(string[] args)
{
Result result = GetResult("OS234");
Console.WriteLine("String part: {0} int part: {1}", result.StringPart, result.IntPart);
result = GetResult("AA4230 ");
Console.WriteLine("String part: {0} int part: {1}", result.StringPart, result.IntPart);
result = GetResult("ABCD4321");
Console.WriteLine("String part: {0} int part: {1}", result.StringPart, result.IntPart);
Console.ReadKey();
}
}
Just use the substring function and set position inside the bracket.
String id = "DON123";
System.out.println("Id nubmer is : "+id.substring(3,6));
Answer:
Id number is: 123
use Split to seprate string from sting that use tab \t and space
string s = "sometext\tsometext\tsometext";
string[] split = s.Split('\t');
now you have an array of string that you want too easy

Truncate string on whole words in .NET C#

I am trying to truncate some long text in C#, but I don't want my string to be cut off part way through a word. Does anyone have a function that I can use to truncate my string at the end of a word?
E.g:
"This was a long string..."
Not:
"This was a long st..."
Try the following. It is pretty rudimentary. Just finds the first space starting at the desired length.
public static string TruncateAtWord(this string value, int length) {
if (value == null || value.Length < length || value.IndexOf(" ", length) == -1)
return value;
return value.Substring(0, value.IndexOf(" ", length));
}
Thanks for your answer Dave. I've tweaked the function a bit and this is what I'm using ... unless there are any more comments ;)
public static string TruncateAtWord(this string input, int length)
{
if (input == null || input.Length < length)
return input;
int iNextSpace = input.LastIndexOf(" ", length, StringComparison.Ordinal);
return string.Format("{0}…", input.Substring(0, (iNextSpace > 0) ? iNextSpace : length).Trim());
}
My contribution:
public static string TruncateAtWord(string text, int maxCharacters, string trailingStringIfTextCut = "…")
{
if (text == null || (text = text.Trim()).Length <= maxCharacters)
return text;
int trailLength = trailingStringIfTextCut.StartsWith("&") ? 1
: trailingStringIfTextCut.Length;
maxCharacters = maxCharacters - trailLength >= 0 ? maxCharacters - trailLength
: 0;
int pos = text.LastIndexOf(" ", maxCharacters);
if (pos >= 0)
return text.Substring(0, pos) + trailingStringIfTextCut;
return string.Empty;
}
This is what I use in my projects, with optional trailing. Text will never exceed the maxCharacters + trailing text length.
If you are using windows forms, in the Graphics.DrawString method, there is an option in StringFormat to specify if the string should be truncated, if it does not fit into the area specified. This will handle adding the ellipsis as necessary.
http://msdn.microsoft.com/en-us/library/system.drawing.stringtrimming.aspx
I took your approach a little further:
public string TruncateAtWord(string value, int length)
{
if (value == null || value.Trim().Length <= length)
return value;
int index = value.Trim().LastIndexOf(" ");
while ((index + 3) > length)
index = value.Substring(0, index).Trim().LastIndexOf(" ");
if (index > 0)
return value.Substring(0, index) + "...";
return value.Substring(0, length - 3) + "...";
}
I'm using this to truncate tweets.
This solution works too (takes first 10 words from myString):
String.Join(" ", myString.Split(' ').Take(10))
Taking into account more than just a blank space separator (e.g. words can be separated by periods followed by newlines, followed by tabs, etc.), and several other edge cases, here is an appropriate extension method:
public static string GetMaxWords(this string input, int maxWords, string truncateWith = "...", string additionalSeparators = ",-_:")
{
int words = 1;
bool IsSeparator(char c) => Char.IsSeparator(c) || additionalSeparators.Contains(c);
IEnumerable<char> IterateChars()
{
yield return input[0];
for (int i = 1; i < input.Length; i++)
{
if (IsSeparator(input[i]) && !IsSeparator(input[i - 1]))
if (words == maxWords)
{
foreach (char c in truncateWith)
yield return c;
break;
}
else
words++;
yield return input[i];
}
}
return !input.IsNullOrEmpty()
? new String(IterateChars().ToArray())
: String.Empty;
}
simplified, added trunking character option and made it an extension.
public static string TruncateAtWord(this string value, int maxLength)
{
if (value == null || value.Trim().Length <= maxLength)
return value;
string ellipse = "...";
char[] truncateChars = new char[] { ' ', ',' };
int index = value.Trim().LastIndexOfAny(truncateChars);
while ((index + ellipse.Length) > maxLength)
index = value.Substring(0, index).Trim().LastIndexOfAny(truncateChars);
if (index > 0)
return value.Substring(0, index) + ellipse;
return value.Substring(0, maxLength - ellipse.Length) + ellipse;
}
Heres what i came up with. This is to get the rest of the sentence also in chunks.
public static List<string> SplitTheSentenceAtWord(this string originalString, int length)
{
try
{
List<string> truncatedStrings = new List<string>();
if (originalString == null || originalString.Trim().Length <= length)
{
truncatedStrings.Add(originalString);
return truncatedStrings;
}
int index = originalString.Trim().LastIndexOf(" ");
while ((index + 3) > length)
index = originalString.Substring(0, index).Trim().LastIndexOf(" ");
if (index > 0)
{
string retValue = originalString.Substring(0, index) + "...";
truncatedStrings.Add(retValue);
string shortWord2 = originalString;
if (retValue.EndsWith("..."))
{
shortWord2 = retValue.Replace("...", "");
}
shortWord2 = originalString.Substring(shortWord2.Length);
if (shortWord2.Length > length) //truncate it further
{
List<string> retValues = SplitTheSentenceAtWord(shortWord2.TrimStart(), length);
truncatedStrings.AddRange(retValues);
}
else
{
truncatedStrings.Add(shortWord2.TrimStart());
}
return truncatedStrings;
}
var retVal_Last = originalString.Substring(0, length - 3);
truncatedStrings.Add(retVal_Last + "...");
if (originalString.Length > length)//truncate it further
{
string shortWord3 = originalString;
if (originalString.EndsWith("..."))
{
shortWord3 = originalString.Replace("...", "");
}
shortWord3 = originalString.Substring(retVal_Last.Length);
List<string> retValues = SplitTheSentenceAtWord(shortWord3.TrimStart(), length);
truncatedStrings.AddRange(retValues);
}
else
{
truncatedStrings.Add(retVal_Last + "...");
}
return truncatedStrings;
}
catch
{
return new List<string> { originalString };
}
}
I use this
public string Truncate(string content, int length)
{
try
{
return content.Substring(0,content.IndexOf(" ",length)) + "...";
}
catch
{
return content;
}
}

Categories