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 have a problem regarding create squence of number, but i face some problem like given below. I want a number Format Like UK 0000, there are some conditon applied:
It start from UK 0001
After reaches 9 record then 10th record is like UK 0010
If all digit fill Like UK 9999 then next record show like UK 10000 and so on
Please help me for this, It can use any platform like
jquery
c#
sql etc...
in c#, you can do this
string s = "UK";
int counter = 0;
if (counter < 10000)
result = s + counter++.ToString().PadLeft(4, '0');
else
result = s + counter++.ToString();
Output: UK0000,UK0001,UK0002......
IEnumerable<int> numbers= Enumerable.Range(1, 10000).Select(x=>x);
var list = squares.Select(numbers => "UK" + numbers.ToString("0000")).ToList();
try
List<string> lista = new List<string>();
for (int num = 0; num < 12000; num++)
{
lista.Add(string.Format("UK {0}", num > 999 ? num.ToString() : num.ToString().PadLeft(4, '0')));
}
USING JQUERY - Here is a working example : jsfiddle
Jquery :
$(document).ready(function () {
var prefix = "UK";
var max = 4;
var limit = 10004;
for (var i = 0; i < limit - 1; i++) {
var a = prefix + pad(i, max);
$("#msg").append(a);
$("#msg").append("<br/>");
}
function pad(str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
});
Related
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 3 years ago.
Improve this question
I have two integers, say 4 and 11, and I have a string for example Month04
I want to able to compare that string to the range of numbers between 11 and 4.
So in the other ways a loop which has (if Month04.contains(11,10,9,8,7,6,5,4) then
How can I solve that elegantly?
Regards
You can use any() to check if the number exists in the string and Enumerable.Range() to create the numbers list
string month = "Month04";
int num1 = 4;
int num2 = 11;
IEnumerable<int> numbersList = Enumerable.Range(num1, num2 - num1 + 1) ;
if (numbersList.Any(x => month.Contains(x.ToString())))
{
// then
}
I suggest you create a generic method for this:
public static bool CheckNameInRangeOfIntegers(int lowerBound, int upperBound, string inputString)
{
List<int> rangeOfIntegers=Enumerable.Range(lowerBound,(upperBound-lowerBound + 1)).ToList();
return rangeOfIntegers.Any(x=>inputString.Contains(x.ToString()));
}
Example can be called as :
Console.WriteLine(CheckNameInRangeOfIntegers(4,11,"Month4")); // true
Console.WriteLine(CheckNameInRangeOfIntegers(4,11,"Month1")); // false
Please note: Be clear about your scenarios, if you are processing with .Any() followed by a .Contains() then you will be in trouble in some cases, for example, lowerBound = 1, uppeBound=10, and inputString="Month11"
If your all months ends with digits then you can try below,
int startIndex = 4; //I used variables to define starting index and end index
int endIndex = 11;
List<int> numbers = Enumerable.Range(startIndex, (endIndex-startIndex + 1)).ToList();
if (numbers.Any(x => "Month04".EndsWith(x.ToString())))
{
//Your business logic
}
Here's yet another example using the Regex pattern \d+ which will match every digit group in the string (04 in this case). Then we can cast those matches to integers, and finally, Linq expressions Intersect() and .Any() will return true if any matching values exist between the two integer collections.
string s = "Month04";
Regex pattern = new Regex(#"\d+");
var numbersInString = pattern.Matches(s).Cast<Match>().Select(x = int.Parse(x.Value));
int lowerBound = 4;
int upperBound = 11;
var range = Enumerable.Range(lowerBound, upperBound - lowerBound + 1);
if (numbersInString.Intersect(range).Any())
{
//Match
}
This way:
int[] numbers = new int[] { 11, 10, 9, 8, 7, 6, 5, 4 };
string str = "Month04";
int number = int.Parse(str.Replace("Month", ""));
if (numbers.Contains(number))
{
Console.WriteLine("YEEE!");
}
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 want to make every other letter uppercase, how do I do that?
Code:
String a = ("aábdeéðfghiíjklmnoóprstuúvxyýþæö");
for (int i=0; i < a.Length; i++)
{
Console.Write(a.ToUpper()[i]+ ",");
}
Using Linq:
string a = "aábdeéðfghiíjklmnoóprstuúvxyýþæö";
var converted =
new string(a.Select((ch, i) => ((i % 2) == 0) ? ch : Char.ToUpper(ch)).ToArray());
Console.WriteLine(converted);
Increment your loop by 2.
Example:
String a = ("aábdeéðfghiíjklmnoóprstuúvxyýþæö");
for (int i=0; i<a.Length; i+=2)
Console.Write(a.ToUpper()[i]+ ",");
For every even alphabet start loop from 0 and for odd start from 1.
Linq answer is very good and has the advantage to be one liner, but a normal loop here is twice faster than the Linq solution
char[] a = "aábdeéðfghiíjklmnoóprstuúvxyýþæö".ToCharArray();
for (int i = 0; i < a.Length; i++)
{
if (i % 2 != 0)
{
a[i] = Char.ToUpper(a[i]);
}
}
string result = new string(a);
Using LINQ to go through each char in the string. If it is divisible by 2 then that means its every other letter. So make that upper case, if not divisible by 2 then leave it as it is. Rejoin all the chars together in an array then convert that back into a string.
String a = ("aábdeéðfghiíjklmnoóprstuúvxyýþæö");
var convertedString = new string(a
.Select((c, i) => (i + 1) % 2 == 0 ? Char.ToUpper(c) : c)
.ToArray());
String a = ("aábdeéðfghiíjklmnoóprstuúvxyýþæö");
for (int i=0; i<a.Length; i++)
{
if (i % 2 == 0)
{
a = a.Substring(0, i) + a.Substring(i, 1).ToUpper() + a.Substring(i);
}
}
The % symbol is modulo, in this context if the index if divisible by 2 make the symbol upper case.
EDIT: as correctly pointed out, string are immutable, I've edited appropriately. This most likely isn't the most efficient way of doing this, I'd recommend using LINQ for a more efficient algorithm
You can use Linq.
string oldString = "aábdeéðfghiíjklmnoóprstuúvxyýþæö";
string alternatedString = string.Concat(
oldString.ToLower().Select((character, index) => index % 2 == 0 ? character : char.ToUpper(character)));
Output: aÁbDeÉðFgHiÍjKlMnOóPrStUúVxYýÞæÖ
Or
string oldString = "aábdeéðfghiíjklmnoóprstuúvxyýþæö";
StringBuilder alternatedString = new StringBuilder();
for(int index=0; index<oldString.Length; index++)
{
if(index % 2 == 0)
alternatedString.Append(oldString[index].ToString().ToLower());
else
alternatedString.Append(oldString[index].ToString().ToUpper());
}
Output: aÁbDeÉðFgHiÍjKlMnOóPrStUúVxYýÞæÖ
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 7 years ago.
Improve this question
I need to write a for loop that prints 49 through 1, with each value separated by a comma. So, it must not print a comma after the last value.
I have this so far and have no clue , after an hour of research, what else to do.
For (int i = 49; i >= 1; i--)
{
Console.WriteLine(i + ",");
}
Just check where you are in your loop to know if you need to print the comma.
public static void Test()
{
for (int i = 49; i >= 1; i--)
{
Console.WriteLine(i + (i != 1 ? "," : ""));
}
Console.ReadLine();
}
Check if you are at the last item, and don't write the comma in that case:
for (int i = 49; i >= 1; i--) {
Console.Write(i);
if (i > 1) {
Console.Write(",");
}
Console.WriteLine();
}
(There are alternatives that are a little more elegant, but this is closest to your original code. You can for example write the comma before the number and skip the first comma.)
You can use String.Join
List<string> numbers = new List<string>();
for (int i = 49; i >= 1; i--) {
numbers.Add(i.ToString());
}
string numberWithCommas = String.Join(",", numbers);
Console.WriteLine(numberWithCommas);
Or you can put in a if condition to check for the last element and conditionally print your comma.
The String.Join would be a neater way to do this operation. However as pointed out by #CommuSoft, if you are doing this operation for a large list of numbers, the memory used may be high in this operation.
Try this:
for (int i = 49; i >= 1; i--)
{
Console.Write("{0}{1}", i, i == 1 ? string.Empty : ",");
}
Your not keeping track of your value.
var content = String.Empty;
for(var i = 49; i >= 1; i--)
content += (i + ",");
Console.WriteLine(content);
Once you have a value, then you apply it. The problem your having is the scope never remains, it applies to a new line.
The value of i determines when to add the comma:
For (int i = 49; i >= 1; i--)
{
Console.WriteLine(i >= 1 ? i + "," : i);
}
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
For example if I were to have
Textbox1.Text = "aaaabbbccDdff";
How would I convert that to a letter and numeral representation of the letters based on how many of them are in a row, ie having it turn into
Textbox2.Text = "a4b3c2Ddf2";
Try with this:
string s = Textbox1.Text; //"aaaabbbccfffff";
string r = "";
int count = 0;
char currChar = s[0];
for(int i = 0; i < s.Length + 1; i++)
{
if(i >= s.Length || currChar != s[i])
{
r += currChar + count.ToString();
count = 1;
if(i < s.Length)
currChar = s[i];
}
else count++;
}
Textbox2.Text = r;
For the Linq fanatics:
var r = string.Join("", s.GroupBy(c=>c).Select(x=>x.Key+x.Count().ToString()));
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
My program has no compile errors but the output is incorrect. Example input:
size of array: 5
input numbers: 5 4 3 2 1
//sorted: 1 2 3 4 5
search: 1
output: number 1 found at index 4
the output should be number 1 found at index 0 since the numbers were sorted already. How will I change it to this.
int[] nums = new int[100];
int SizeNum;
bool isNum = false;
private void ExeButton_Click(object sender, EventArgs e)
{
int i, loc, key;
Boolean found = false;
string SizeString = SizeTextBox.Text;
isNum = Int32.TryParse(SizeString, out SizeNum);
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
for (int j = 0; j < numsInString.Length; j++)
{
nums[j] = int.Parse(numsInString[j]);
}
if (SizeNum == numsInString.Length)
{
Array.Sort(numsInString);
key = int.Parse(SearchTextBox.Text);
ResultText.AppendText("Sorted: ");
for (i = 0; i < SizeNum; i++)
ResultText.AppendText(" " + numsInString[i]);
ResultText.AppendText("\n\n");
{
for (loc = 0; loc < SizeNum; loc++)
{
if (nums[loc] == key)
{
found = true;
break;
}
}
if (found == true)
ResultText.AppendText("Number " + key + " Found At Index [" + loc + "]\n\n");
else
ResultText.AppendText("Number " + key + " Not Found!\n\n");
}
}
}
You're sorting numsInString but then searching nums. nums is being populated before the search, so you're seeing the results of searching the unsorted numbers.
Once you've parsed numsInStrings into nums, you should be working with the latter array only. Make sure that's the one you're sorting and searching through.
In other words, once you replace the current sort call with
Array.Sort(nums);
your code will be fine.
Updated:
You actually need another fix. Right now, you're initializing nums to be an array of size 100. By default, each element will be 0. So even though you put numbers in the first five elements, when you sort the array, you end up with 95 0's, followed by 1 2 3 4 5.
You should delay initializing nums until you've seen how big numsInString is:
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
nums = new int[numsInString.Length];
for (int j = 0; j < numsInString.Length; j++)
{
nums[j] = int.Parse(numsInString[j]);
}
Now when you sort nums, you'll see only the numbers you entered.
you are sorting the numsInString array, but still searching into the nums array.
for (loc = 0; loc < SizeNum; loc++)
{
if (numsInString[loc] == key)
{
found = true;
break;
}
}
You're parsing numsInString then you're sorting it. (I suspect the sort won't do what you want, either.)
I think you really want to be sorting nums instead:
Array.Sort(nums);
Having said that, there are simpler ways of achieving the end result - such as using IndexOf to find the index of a value in an array.
It's also rather unclear why you've got braces here:
for (i = 0; i < SizeNum; i++)
ResultText.AppendText(" " + numsInString[i]);
ResultText.AppendText("\n\n");
{
...
}
That makes it look like you've got a loop with a body, but it's actually equivalent to:
for (i = 0; i < SizeNum; i++)
{
ResultText.AppendText(" " + numsInString[i]);
}
ResultText.AppendText("\n\n");
{
...
}
... the braces serve no purpose here, and merely harm readability.