how to create int to string like this 50-> "00050" [duplicate] - c#

This question already has answers here:
Convert int (number) to string with leading zeros? (4 digits) [duplicate]
(4 answers)
Closed 5 years ago.
Hello i am trying to process character arrays.
I want to assign the number 50 as string value "00050". How can I do it ?
enter code here
string strRpc(int NumstrRpcSendLen)
{
int digit = Convert.ToInt32( Math.Floor(Math.Log10(NumstrRpcSendLen + 5) + 1));
int len = 0;
char[] d = new char[5];
string result= null;
while (len<5)
{
if (len<digit)
{
d[len] = '0';
}
else
{
}
len++;
}
return result;
}

I'm not sure what your code is doing, but there's a string format specifier for that:
var x = 50.ToString("D5");
//x = "000050"
Look at the documentation for more help

You could try it
var result = 50.ToString("00000");

Related

C# Palindrome Test [duplicate]

This question already has answers here:
Check if a string is a palindrome
(33 answers)
Closed 3 years ago.
I need to create a IsPalindrome function where it will determine if a provided string is a palindrome. Alphanumeric chars will be considered when evaluating whether or not the string is a palindrome. With this said, I am having trouble trying to disreguard the spaces and the Caps. Here is what my function looks like now.
If this makes a difference: After this function is done I will then have to have parse a JSON file and have each element in the "strings" array, into the IsPalindrome function.
Any tips?
private static bool IsPalindrome(string value)
{
var min = 0;
var max = value.Length - 1;
while (true)
{
if (min > max)
return true;
var a = value[min];
var b = value[max];
if (if (char.ToLower(a) == char.ToLower(b))
{
return true;
}
else {
return false;
}
min++;
max--;
}
The way I'd do this is to turn the string into an array of characters, skipping non-letter characters, and making all the characters lowercase. Then, I'd use an index to check if the first half of the array is equal to the last. Something like this:
public static bool IsPalindrome(string value)
{
char[] forwards = (from c in value.ToLower().ToCharArray() where char.IsLetter(c) select c).ToArray();
int middle = (forwards.Length / 2) + 1;
for (int i = 0; i < middle; i++)
if (forwards[i] != forwards[forwards.Length - 1 - i])
return false;
return true;
}
That first line uses LINQ to make the array, so you need a using System.Linq;

How to check if a string ends with a number, without regex? [duplicate]

This question already has answers here:
Extract number at end of string in C#
(9 answers)
Regex for number at the end of string?
(5 answers)
Closed 3 years ago.
I need to check if the last character of a string ends with an int. I would like to avoid using a regular expression, because I think it is very hard, but if there is no smoother way of doing it, I will try it.
I basically tried something that looks like this:
text.EndsWith(INTEGER)]
Boolean result = char.IsDigit(text[text.Length - 1]);
using linq Last method and Isdigit function
bool isDigit = Char.IsDigit(("one1").Last());
Isolate the last character and try parse it to integer:
private static bool IsStringEndsWithDigit(string str)
{
if (String.IsNullOrEmpty(str))
{
return false;
// or throw an exception
// throw new Exception("string can not be empty");
}
string last = str.Substring(str.Length - 1, 1);
int num;
var isNum = int.TryParse(last, out num);
return isNum;
}
var lastChar = text.Last();
var endsWithNum = lastChar >= '0' && lastChar <= '9';
string s = "hello world0";
int len = s.Length;
List<char> digits = new List<char>(){'0','1','2','3','4','5','6','7','8','9'};
if (digits.Contains(s[len - 1]))
{
Console.WriteLine("last character is digits");
}

How to find out the duplicate characters in a string? [duplicate]

This question already has answers here:
How do I get an array of repeated characters from a string using LINQ?
(3 answers)
Closed 7 years ago.
I take a string with integer count
int count=0;
string s="wow"
and i am using foreach loop to count number of characters in a specified string
foreach(char ch in s)
{
count++
}
so how can i count those characters which are repeated in my string like 'w'.
Try this )
string test = "aababc";
var result = test.GroupBy(c => c).Where(c => c.Count() > 1).Select(c => new { charName = c.Key, charCount = c.Count()});
Do like this
string s="wow";
int repeats= s.Length - s.ToCharArray().Distinct().Count();

How to get text contained between brackets [duplicate]

This question already has answers here:
How do I extract text that lies between parentheses (round brackets)?
(19 answers)
Closed 8 years ago.
I have 3 different string values in my console application:
Student A (AA.1)
Student(1) B (AA.2)
Student B
Would like to get value from backet:
AA.1, AA.2
Thanks. I have used split, however will encounter error because of Student B does not have any bracket and Student(1) B (AA.2) have 2 brackets.
Current Code
char[] targetExpression = new char[] { '(', ')' };
string title = "Student A (AA.1)";
Console.WriteLine(title.Split(targetExpression)[1]);
looking for something like this?
/.*\(([^)]*)\)$/
A function to get a string within characters
string GetStirngWithiin(string SourceString, char startChar, char endChar,int StartFrom=0)
{
SourceString = SourceString.Substring(StartFrom);
int startFrom=SourceString.IndexOf(startChar);
int EndAt=SourceString.IndexOf(endChar);
if ((startFrom > -1) && (EndAt >-1))
{
int SubStrLength = EndAt - startFrom - 1;
if (SubStrLength > 0)
{
string Result = SourceString.Substring(startFrom + 1, SubStrLength);
return Result;
}
}
return "";
}
you can use the function calls as
string str1 = GetStirngWithiin("Student A (AA.1)",'(',')');
string str2 = GetStirngWithiin("Student(1) B (AA.2))", '(', ')',10);
using with Student B will return a blank string.

Long path with ellipsis in the middle [duplicate]

This question already has answers here:
Function to shrink file path to be more human readable
(9 answers)
Closed 7 years ago.
I would like to truncate a long path to specific length. However, I want to have the ellipsis in the middle.
for example: \\my\long\path\is\really\long\and\it\needs\to\be\truncated
should become (truncated to 35 chars): \\my\long\path\is...to\be\truncated
Is there a standard function or extension method available?
There is no standard function or extension method, so you will have to roll your own.
Check for length and use something like;
var truncated = ts.Substring(0, 16) + "..." + ts.Substring((ts.Length - 16), 16);
Here is what I use. It very nicely create ellipsis in the middle of a path and it also allows you to speciy any length or delimiter.
Note this is an extension method so you can use it like so `"c:\path\file.foo".EllipsisString()
I doubt you need the while loop, in fact you probably don't, I was just too busy to test properly
public static string EllipsisString(this string rawString, int maxLength = 30, char delimiter = '\\')
{
maxLength -= 3; //account for delimiter spacing
if (rawString.Length <= maxLength)
{
return rawString;
}
string final = rawString;
List<string> parts;
int loops = 0;
while (loops++ < 100)
{
parts = rawString.Split(delimiter).ToList();
parts.RemoveRange(parts.Count - 1 - loops, loops);
if (parts.Count == 1)
{
return parts.Last();
}
parts.Insert(parts.Count - 1, "...");
final = string.Join(delimiter.ToString(), parts);
if (final.Length < maxLength)
{
return final;
}
}
return rawString.Split(delimiter).ToList().Last();
}
This works
// Specify max width of resulting file name
const int MAX_WIDTH = 50;
// Specify long file name
string fileName = #"A:\LongPath\CanBe\AnyPathYou\SpecifyHere.txt";
// Find last '\' character
int i = fileName.LastIndexOf('\\');
string tokenRight = fileName.Substring(i, fileName.Length - i);
string tokenCenter = #"\...";
string tokenLeft = fileName.Substring(0, MAX_WIDTH-(tokenRight.Length + tokenCenter.Length));
string shortFileName = tokenLeft + tokenCenter + tokenRight;

Categories

Resources