Split long string WP7 - c#

How do I split a long string ?
Input :
ABCDEFGHI
Output :
ABC, DEF, GHI

Use
string str = "ABCDEFGHI";
List<string> lst = new List<string>();
string temp = "";
for(int i = 0; i < str.Length; i++)
{
temp = str[i].ToString();
if((i + 1) % 3 == 0)
{
lst.Add(temp);
temp = "";
}
}
string final_str = string.Join(", ", lst);

Assuming this is a very long string, use a string builder to do your concatenating. And use substring to build the individually grouped strings. This will save you on memory.
string longString = "ABCDEFGHIJK";
int groupingLength = 3;
var stringLength = longString.Length;
var startingLength = Math.Min(longString.Length, groupingLength);
var startingString = longString.Substring(0, startingLength);
var sb = new StringBuilder(startingString);
if (stringLength > groupingLength)
{
for(int i = groupingLength; i < stringLength; i = i + groupingLength)
{
var subStringLength = Math.Min(stringLength - i, groupingLength);
var groupedString = longString.Substring(i, subStringLength);
sb.Append(", ").Append(groupedString);
}
}
var finalString = sb.ToString();

Related

How to mask string after first character

Let's say I have a string that consists of a person's name:
var name = "Jason, Bruno Mars";
How do I mask the string with X for the name behind the comma and returns:
var name = "Jason, BXXXX MXXX";
I have tried using the following methods but only front characters are masked:
string first, second, output;
bool hasSpace, hasComma;
int int_LENGTH;
var name = "Jason, Bruno Mars";
hasComma = name.Contains(",");
if (hasComma == true)
{
int_LENGTH = name.IndexOf(",");
if (int_LENGTH > 0)
{
first = name.Substring(0, int_LENGTH);
}
second = string.Join(",", name.Split(" ").Skip(1));
hasSpace = second.Contains(" ");
if (hasSpace == true)
{
second = string.Concat(new string('X', 12), second.Substring(second.Length - 4));
output = first + "," + second;
}
}
Anyone has a better idea of how can I achieve the same result in a more efficient way?
Another option, using Regex.Matches to select the name parts except the first letter. The regex collects all string parts separated by a space, skipping what's before the comma.
The collections of Matches is then passed to Linq's Aggregate() method to perform the substitution.
A StringBuilder is used to store the strings generated by its own Replace() method:
string theName = "Jason Et Alt., Bruno Mars And More Names";
var matches = Regex.Matches(theName, #"(?!.*?,)\s+?.(\w+)");
string outName = matches.OfType<Match>().Aggregate(new StringBuilder(theName), (sb, m) =>
sb.Replace(m.Groups[1].Value, new string('X', m.Groups[1].Length))).ToString();
outname = Jason Et Alt., BXXXX MXXX AXX MXXX NXXXX
static string MaskName(string name)
{
string maskedString = string.Empty;
string[] names = name.Split(',');
if (names.Length > 0)
{
maskedString = names[0] + ",";
}
if (names.Length > 1)
{
string[] arrName = names[1].Split(' ');
foreach (string s in arrName)
{
if (s.Length > 0)
maskedString += " " + s[0].ToString().PadRight(s.Length, 'X');
}
}
return maskedString;
}
Using This code..
static string MaskName(string name)
{
string maskedString = string.Empty;
string[] names = name.Split(',');
if (names.Length > 0)
{
maskedString = names[0] + ",";
}
if (names.Length > 1)
{
string[] arrName = names[1].Split(' ');
foreach (string s in arrName)
{
if (s.Length > 0)
maskedString += " " + s[0].ToString().PadRight(s.Length, 'X');
}
}
return maskedString;
}
Output :-
Try This
private string ReturnMaskedName(string name)
{
string temporary = "";
var newname = (name.Split(new string[] { "," }, StringSplitOptions.None)[1].Trim().Split(new String[] { " " }, StringSplitOptions.None));
foreach (string allnames in newname)
{
temporary = temporary + " " + allnames[0].ToString() + new string('X', allnames.Length - 1);
}
return name.Split(new string[] { " " }, StringSplitOptions.None)[0] + " " + temporary;
}
Efficient way of masking without Split, Regex, and using System.Linq:
For C# version < 7.2:
static string MaskName(string name)
{
int indexOfComma = name.IndexOf(',');
if (indexOfComma != -1)
{
char[] temp = name.ToCharArray();
bool isFirstChar = true;
for (int i = indexOfComma + 1; i < temp.Length; i++)
{
if (temp[i] == ' ')
isFirstChar = true;
else if (isFirstChar)
isFirstChar = false;
else
temp[i] = 'X';
}
return new string(temp);
}
else
{
return name;
}
}
For C# version >= 7.2:
static string MaskName(ReadOnlySpan<char> name)
{
int indexOfComma = name.IndexOf(',');
if (indexOfComma != -1)
{
Span<char> temp = stackalloc char[name.Length];
name.CopyTo(temp);
bool isFirstChar = true;
for (int i = indexOfComma + 1; i < temp.Length; i++)
{
if (temp[i] == ' ')
isFirstChar = true;
else if (isFirstChar)
isFirstChar = false;
else
temp[i] = 'X';
}
return new string(temp);
}
else
{
return name.ToString();
}
}
private string MaskName(string name)
{
var parts = name.Split(',');
var subparts = parts[1].Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
for (var i = 0; i < subparts.Length; i++)
{
var subpart = subparts[i];
subparts[i] = subpart[0] + new string('X', subpart.Length - 1);
}
return parts[0] + ", " + string.Join(" ", subparts);
}

how to fix stringBuilder to string and reverse?

I have a StringBuilder result and I want to reverse it but in C# the StringBuilder doesn't support .Reverse() so first I cast it to a string and then I reverse it and add a "$" to the end of string.
but the answer is like this:
System.Linq.Enumerable+<ReverseIterator>d__75`1[System.Char]" string
how can I fix this?
StringBuilder result = new StringBuilder();
List<string> matrix = new List<string>();
List<int> indexes = new List<int>();
for (int i = 0; i < bwt.Length; i++)
{
matrix.Add("" + bwt[i]);
indexes.Add(i);
}
indexes.Sort((o1, o2) => matrix[o1].CompareTo(matrix[o2]));
int current = indexes[0];
for (int i = 0; i < bwt.Length - 1; i++)
{
int index = indexes.IndexOf(current);
string next = bwt[index].ToString();
result.Append(next);
current = index;
}
// return result.ToString().ToString() + "$";
StringBuilder allows you to access and manipulate the characters through their indexes.
string stringToReverse = "abcdefghijk";
var sb = new StringBuilder(stringToReverse);
for (int i = 0, j = sb.Length - 1; i < sb.Length / 2; i++, j--) {
char temp = sb[i];
sb[i] = sb[j];
sb[j] = temp;
}
string reversed = sb.ToString();
But I made a Test which shows that #Mendhak's version is faster. One million repetitions with strings of length 100
StringBuilder: 974 ms
Mendhak: 209 ms
So on my PC it takes just 209 ns to reverse the string with Mendhak's solution. Just because a solution looks faster it must not be faster. Array.Reverse calls the external method private static extern bool TrySZReverse(Array array, int index, int count); which is highly optimized.
The test:
static class ReverseString
{
const string stringToReverse = "abcdex.dfkjvhw4o5i8yd,vfjhe4iotuwyflkcjadhrlniqeuyfmln mclf8yuertoicer,tpoirsd,kfngoiw5r8t7ndlrgjhfg";
public static string TestStringBuilder()
{
var sb = new StringBuilder(stringToReverse);
for (int i = 0, j = sb.Length - 1; i < sb.Length / 2; i++, j--) {
char temp = sb[i];
sb[i] = sb[j];
sb[j] = temp;
}
return sb.ToString();
}
// By Mendhak
public static string TestArrayReverse()
{
char[] arr = stringToReverse.ToString().ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
public static void Compare()
{
string result1 = TestStringBuilder();
string result2 = TestArrayReverse();
Console.WriteLine($"Are result1 and 2 equal? {result1 == result2}");
Measure("StringBuilder", TestStringBuilder);
Measure("Array.Reverse", TestArrayReverse);
Console.ReadKey();
}
public static void Measure(string method, Func<string> sut)
{
const int NTests = 1000000;
var stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < NTests; i++) {
sut();
}
stopWatch.Stop();
Console.WriteLine($"{method} = {stopWatch.ElapsedMilliseconds} ms");
}
}
You will need to take a few extra steps to reverse your string. Build it as you normally would in your stringbuilder (result), then
char[] arr = result.ToString().ToCharArray();
Array.Reverse(arr);
return new string(arr) + "$";

How to split of string and for each determined character found add a new line

For example:
I have this:
string commaSeparatedString = "124,45415,1212,4578,233,968,6865,32545,4545";
I want to do that for each 4 found comma add a new line
124-45415-1212-4578
233-968-6865-32545
4545
What about this:
string str = "124,45415,1212,4578,233,968,6865,32545,4545";
var result = string.Join("-", sss.Split(',').Select((c, index) => (index + 1) % 4 == 0 ?
c + Environment.NewLine : c));
Just don't forget to add LINQ to your using directives first:
using System.Linq;
Try this:
const int batch = 4;
var target = "124,45415,1212,4578,233,968,6865,32545,4545";
var items = target.Split(',');
var results = new List<string>();
var continue = false;
var step = 0;
do
{
var slide = items.Skip(step++ * batch).Take(batch);
continue = slide.Count() == batch;
results.Add(string.Join('-', slide));
}while(continue);
Here you go :
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.Write(SplitOnChar("124,45415,1212,4578,233,968,6865,32545,4545",',',4));
Console.ReadKey();
}
private static string SplitOnChar(string input, char theChar, int number)
{
string result = "";
int seen = 0;
int lastSplitIndex = 0;
for(int i = 0; i< input.Length;i++)
{
char c = input[i];
if (c.Equals(theChar))
{
seen++;
if (seen == number)
{
result += input.Substring(lastSplitIndex + 1, i - lastSplitIndex -1);
result += Environment.NewLine;
lastSplitIndex = i;
seen = 0;
}
}
}
result += input.Substring(lastSplitIndex + 1);
result = result.Replace(theChar, '-');
return result;
}
}
}

Removing Leading Zeros in a Char Array

I'm attempting to subtract two strings (of theoretically infinite length) without the use of libraries like BigIntbut I was wondering if anybody has any good ideas on how to remove the leading zeros in the corner cases like the one below?
static void Main(string[] args)
{
Console.WriteLine(Subtract("10", "10005"));
}
static string ReverseInput(string inputString)
{
char[] charArray = inputString.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
static string Subtract(string firstNumInput, string secondNumInput)
{
string firstNum = String.Empty;
string secondNum = String.Empty;
bool negative = false;
// Reverse order of string input
if (firstNumInput.Length > secondNumInput.Length)
{
firstNum = ReverseInput(firstNumInput);
secondNum = ReverseInput(secondNumInput);
}
else if (firstNumInput.Length < secondNumInput.Length)
{
negative = true;
firstNum = ReverseInput(secondNumInput);
secondNum = ReverseInput(firstNumInput);
}
else if (firstNumInput.Length == secondNumInput.Length)
{
// iterate through string to find largest
}
char[] result = new char[firstNum.Length + 1];
int resultLength = 0;
int carry = 0;
for (int i = 0; i < firstNum.Length; i++)
{
int an = (i < firstNum.Length) ? int.Parse(firstNum[i].ToString()) : 0;
int bn = (i < secondNum.Length) ? int.Parse(secondNum[i].ToString()) : 0;
int rn = an - bn - carry;
if (rn < 0)
{
carry = 1;
rn += 10;
}
else
{
carry = 0;
}
result[resultLength++] = (char)(rn + '0');
}
// create the result string from the char array
string finalResult = ReverseInput(new string(result, 0, resultLength));
if (negative)
{
finalResult = '-' + finalResult;
}
return finalResult;
}
Are you looking for TrimStart?
// create the result string from the char array
string finalResult = ReverseInput(new string(result, 0, resultLength)).TrimStart('0');

String find and replace

I have a string like
string text="~aaa~bbb~ccc~bbbddd";
The input value will be : bbb
So in the above string i should remove the value "~bbb"
The resulting string should be
text="~aaa~ccc~bbbddd";
I'm not sure what are you wanna do but if i've got it you can do this :
private string ReplaceFirstOccurrence(string Source, string Find, string Replace)
{
int Place = Source.IndexOf(Find);
string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
return result;
}
var result =ReplaceFirstOccurrence(text,"~"+input,"");
One way would be:
string text = "~aaa~bbb~ccc~bbbddd";
string newStr = string.Join("~", text.Split('~').Where(r => r != "bbb"));
But if performance is the consideration then consider some other solution
You can use the regular expression #"\bMYWORDTOREPLACE\b" in c# this would be...
using System.Text.RegularExpressions;
myString = Regex.Replace(myString, #"\bbbb\b", "", RegexOptions.IgnoreCase);
This should do the trick:
string searchValue = "bbb";
text = text.Replace(String.Format("~{0}~", searchValue), "~");
Be sure to search for the ending ~ character as well, otherwise you will also replace part of ~bbbddd.
Like this
string str = "~rajeev~ravi";
string strRemove = "rajeev";
string strNew =str.Replace("~"+strRemove ,"");
public static string Replace(this String str, char[] chars, string replacement)
{
StringBuilder output = new StringBuilder(str.Length);
bool replace = false;
if (chars.Length - 1 < 1)
{
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
replace = false;
// int val = Regex.Matches(ch.ToString(), #"[a-zA-Z]").Count;
for (int j = 0; j < chars.Length; j++)
{
if (chars[j] == c)
{
replace = true;
break;
}
}
if (replace)
output.Append(replacement);
else
output.Append(c);
}
}
else
{
int j = 0;
int truecount = 0;
char c1 = '\0';
for (int k = 0; k < str.Length; k++)
{
c1 = str[k];
if (chars[j] == c1)
{
replace = true;
truecount ++;
}
else
{
truecount = 0;
replace = false;
j = 0;
}
if(truecount>0)
{
j++;
}
if (j > chars.Length-1)
{
j = 0;
}
if (truecount == chars.Length)
{
output.Remove(output.Length - chars.Length+1, chars.Length-1);
// output.Remove(4, 2);
if (replace)
output.Append(replacement);
else
output.Append(c1);
}
else
{
output.Append(c1);
}
}
}
return output.ToString();
}
static void Main(string[] args)
{
Console.WriteLine("Enter a word");
string word = (Console.ReadLine());
Console.WriteLine("Enter a word to find");
string find = (Console.ReadLine());
Console.WriteLine("Enter a word to Replace");
string Rep = (Console.ReadLine());
Console.WriteLine(Replace(word, find.ToCharArray(), Rep));
Console.ReadLine();
}
}
This is an old question, but my solution is to create extension function for string.
Like ".ReplaceFirst" Java method.
You need to create static class like Helper and inside that class create static extension function:
public static class Helpers
{
public static string ReplaceFirst(this String str, string find, string replace)
{
int place = str.IndexOf(find);
if (place < 0)
{
return str;
}
//return str.Substring(0, place) + replace + str.Substring(place + find.Length);
return str.Remove(place, find.Length).Insert(place, replace);
}
}
Usage is same like .Replace method...
string text="~aaa~bbb~ccc~bbbddd";
string temp = text.ReplaceFirst("~bbb", ""); //text="~aaa~ccc~bbbddd"
or more
string text="~aaa~bbb~ccc~bbbddd";
string temp = text.ReplaceFirst("~bbb", "").ReplaceFirst("~bbb", ""); //text="~aaa~cccddd"
Well, you could do something like this.
(You only need to input 'bbb')
string text = "~aaa~bbb~ccc~bbbddd";
string input = "bbb";
string output = text.Replace("~" + input + "~", "~");
Console.WriteLine(output);
Output: ~aaa~ccc~bbbddd

Categories