how to separate per 8 digit from string in c#? [closed] - c#

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
string txte = save.ToString();
for (int i = 7; i < save.Length; i= i+8)
{
outs.Append(txte.Substring(i-7,i)+ " ");
}

Given
public static class Extension
{
public static IEnumerable<string> Chunks(this string input, int size)
// select with index
=> input?.Select((x, i) => i)
// filter by chunk
.Where(i => i % size == 0)
// substring out the chunk, or part thereof
.Select(i => input.Substring(i, Math.Min(size,input.Length - i)));
}
Usage
var s = "11111111222222223333333344444444";
foreach (var result in s.Chunks(8))
Console.WriteLine(result);
Console.WriteLine("---");
// or add space
Console.WriteLine(string.Join(" ", s.Chunks(8)));
Results
11111111
22222222
33333333
44444444
---
11111111 22222222 33333333 44444444

As long as you are sure your input has a length which is the exact multiple of 8 characters then this works easily:
var output =
String.Join(
" ",
Enumerable.Range(0, txt.Length / 8).Select(x => txt.Substring(x * 8, 8)));
If you need to ensure that the input has a length which is the multiple of 8 then do this first:
txt = txt.PadRight(txt.Length + txt.Length % 8 == 0 ? 0 : 8 - txt.Length % 8);

Related

How to remove count of specific byte in array C#? [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 3 months ago.
Improve this question
I want to remove bytes from an array, I don't want to remove all bytes 0x6f I just want to remove two only of them. This is my code:
string msg = "gooooooal";
byte[] oldArray = Encoding.GetEncoding(1256).GetBytes(msg);
byte[] newArray = oldArray.Where(b => b != 0x6f).ToArray();
You can first find the position and then remove them
byte[] oldArray = Encoding.GetEncoding(1256).GetBytes(msg);
int howManyToRemove = 2; //How many items to remove
var positions = new List<int>();
int lastPos = -1;
for (int i = 0; i < howManyToRemove; i++)
{
var position = Array.IndexOf(oldArray, (byte)0x6f,lastPos+1);
if (position == -1)
{
break;
}
lastPos=position;
positions.Add(position);
}
byte[] newArray = oldArray.Where((val, idx) => !positions.Contains(idx)).ToArray();
If I understood your problem then if want to delete two occurrences of the letter o from your string because the 0x6f ASCII value is 111 which is the letter o.
and for that, you are making the solution very complex.
if can simply do like this.
string s = "gooooooal";
string output = removeChar(s, 'o'); //output will be gooool
static string removeChar(string s,
char ch)
{
int count = 2;
for (int i = 0; i < s.Length; i++)
{
// If ch is found
if (s[i] == ch && count > 0)
{
s = s.Substring(0, i) +
s.Substring(i + 1);
count--;
}
}
return s;
}

Generate random sequence of AlphaNumeric [closed]

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 1 year ago.
Improve this question
I want a code to generate sequence of Alphanumeric character like LLNNLLNNLL where L is the Letter and N is the number. For example if the length is 5 the sequence will be LLNNL and if the length is 6 the sequence will be LLNNLL and if 7 it would be LLNNLLN.
string alphabets = "ABCDEFGHIJKLMNPQRSTUVWX";
int length = model.VALUE_INT;
string result = "";
for (int i = 0; i < length; i++)
{
int next = _random.Next(23);
result += alphabets.ElementAt(next);
result += _randomNum.Next(1, 9);
}
This is what I have tried but condition is not fulfilling
For each position (value of i) of your output string you need to check if you need a character or an integer.
Since the pattern repeats every 4 positions, you can achieve this using the modulo operator:
for (int i = 0; i < length; i++)
{
switch (i % 4)
{
case 0:
case 1:
int next = _random.Next(23);
result += alphabets.ElementAt(next);
break;
case 2:
case 3:
result += _randomNum.Next(1, 9);
break;
}
}
Or another possibility: Add blocks of LLNN and then truncate the result to the needed length...
for (int i = 0; i <= (length/4); i++)
{
result += alphabets.ElementAt(_random.Next(23));
result += alphabets.ElementAt(_random.Next(23));
result += _randomNum.Next(1, 9);
result += _randomNum.Next(1, 9);
}
result = result.Substring(0,length);
If you want to improve these lines, you can use a StringBuilder

Compare a string to a range of integers [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 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!");
}

How to make only chosen characters uppercase in C# [closed]

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ýÞæÖ

Auto Increment the number [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 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;
}
});

Categories