I wanted to add the numbers (1,2,3) in my string builder before displaying.
If the string builder contains 2- it should have output like this 1) Line text 2) line text and so on
StringBuilder abc = new StringBuilder();
abc.Append("Hi.");
Fun(2, abc);
void Fun(int i, StringBuilder abc)
{
if (i>0)
abc.Append("its me.");
}
// Add some code here to check like if(abc.length>0) // we need to append 1,2,3... to the lines in abc
Console.WriteLine(abc.ToString());
i need the output like
1)Hi. 2) its me.
You can encapsulate logic in different class and use StringBuilder under the hood.
public class ExtendedStringBuilder
{
private StringBuilder _sb;
private int _callNumber;
public ExtendedStringBuilder()
{
_sb = new StringBuilder();
_callNumber = 0;
}
public void Append(string nextString)
{
_sb.AppendFormat("{0} {1}", ++_callNumber, nextString);
}
public override string ToString()
{
return _sb.ToString();
}
}
In this case you do not need to store int value. This is sample:
static void Main(string[] args)
{
var esb = new ExtendedStringBuilder();
esb.Append("Hi.");
esb.Append("its me.");
Console.WriteLine(esb.ToString());
Console.ReadLine();
}
It would be incredibly hard to do it with StringBuilder as index parsing will be ridiculously difficult. I've used List<string> to achieve the same.
List<string> list = new List<string>();
list.Add("Hi");
list.Add("Its me!");
string s = String.Join(" ", list.Select(x => (list.IndexOf(x) + 1).ToString() + ")" + x));
Console.WriteLine(s);
Which gives the output as
1)Hi 2)Its me!
I suggest using Linq, put all the items ("Hi.", "its me.") and get rid of StringBuilder:
using System.Linq;
...
// Or List<string>
string[] items = new string[] {
"Hi.",
"its me."
};
string result = string.Join(" ", items
.Select((item, index) => $"{index + 1}){item}"));
Your code modified (List<string> instead of StringBuilder)
List<string> abc = new List<string>(); // List<string>, not StringBuider
abc.Add("Hi.");
Fun(2, abc);
...
void Fun(int i, IList<string> abc) {
if (abc.Any())
abc.Add("its me.");
}
...
Console.WriteLine(string.Join(" ", abc
.Select((item, index) => $"{index + 1}){item}")));
Related
I am trying to make use of StreamReader and taking data from text files and store it into an array. I am having an issue where I think the fix is simple, but I am stumped. When I print the array, it prints every single token in the txt file instead of the single line of data containing the search name along with the 11 int tokens.
Long_Name.txtsample
public class SSA
{
public void Search()
{
Console.WriteLine("Name to search for?");
string n = Console.ReadLine();
Search(n, "Files/Names_Long.txt");
}
public int[] Search(string targetName, string fileName)
{
int[] nums = new int[11];
char[] delimiters = { ' ', '\n', '\t', '\r' };
using (TextReader sample2 = new StreamReader("Files/Exercise_Files/SSA_Names_Long.txt"))
{
string searchName = sample2.ReadLine();
if (searchName.Contains(targetName))
{
Console.WriteLine("Found {0}!", targetName);
Console.WriteLine("Year\tRank");
}
else
Console.WriteLine("{0} was not found!", targetName);
while (searchName != null)
{
string[] tokensFromLine = searchName.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
int arrayIndex = 0;
int year = 1900;
foreach (string token in tokensFromLine)
{
int arrval;
if (int.TryParse(token, out arrval))
{
nums[arrayIndex] = arrval;
year += 10;
Console.WriteLine("{0}\t{1}", year, arrval);
arrayIndex++;
}
}
searchName = sample2.ReadLine();
}
}
return nums;
}
}
That sure is a lot of code, this snippet does not account for duplicates but if you were willing to work with linq, something like this might help? You could also just iterate over the file_text array using a for-loop and perhaps set your return array in that. Anyway a lot less code to mess with
public int[] Search(string targetName, string fileName)
{
List<string> file_text = File.ReadAllLines("Files/Exercise_Files/SSA_Names_Long.txt").ToList();
List<string> matching_lines = file_text.Where(w => w == targetName).ToList();
List<int> nums = new List<int>();
foreach (string test_line in matching_lines)
{
nums.Add(file_text.IndexOf(test_line));
}
return nums.ToArray();
}
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 4 years ago.
Improve this question
I want to get count the elements in an array but without linq
Example:
string a = "cat";
string b = "dog";
string c = "cat";
string d = "horse";
var list = new List<string>();
list.Add(a);
list.Add(b);
list.Add(c);
list.Add(d);
And
desired result is : cat=2, dog=1, horse=1
Here's one way I could think of using a Dictionary<string, int>:
public static Dictionary<string, int> GetObjectCount(List<string> items)
{
// Dictionary object to return
Dictionary<string, int> keysAndCount = new Dictionary<string, int>();
// Iterate your string values
foreach(string s in items)
{
// Check if dictionary contains the key, if so, add to count
if (keysAndCount.ContainsKey(s))
{
keysAndCount[s]++;
}
else
{
// Add key to dictionary with initial count of 1
keysAndCount.Add(s, 1);
}
}
return keysAndCount;
}
Then get the result back and print to console:
Dictionary<string, int> dic = GetObjectCount(list);
//Print to Console
foreach(string s in dic.Keys)
{
Console.WriteLine(s + " has a count of: " + dic[s]);
}
I am not sure why are you looking for LINQ less solution for this as this could be done very easily and efficiently by it. I strongly suggest you to use it and do it like below :
var _group = list.GroupBy(i => i);
string result = "";
foreach (var grp in _group)
result += grp.Key + ": " + grp.Count() + Environment.NewLine;
MessageBox.Show(result);
Otherwise you can do it like below if you really unable to use LINQ :
Dictionary<string, int> listCount = new Dictionary<string, int>();
foreach (string item in list)
if (!listCount.ContainsKey(item))
listCount.Add(item, 1);
else
listCount[item]++;
string result2 = "";
foreach (KeyValuePair<string, int> item in listCount)
result2 += item.Key + ": " + item.Value + Environment.NewLine;
MessageBox.Show(result2);
The simple solution to your issue is a foreach loop.
string[] myStrings = new string[] { "Cat", "Dog", "Horse", "CaT", "cat", "DOG" };
Console.WriteLine($"There are {GetCount(myStrings, "cat");} cats.");
static int GetCount(string[] strings, string searchTerm) {
int result = 0;
foreach (string s in strings)
if (s == searchTerm)
result++;
return result;
}
Linq does this under the hood. However, unless this is either for optimization of large lists or for learning experience, Linq should be your preferred choice if you know how to use it. It exists to make your life easier.
Another implementation of this would be to simplify the number of calls you need and just write the output in the method:
string[] myStrings = new string[] { "Cat", "Dog", "Horse", "CaT", "cat", "DOG" };
CountTerms(myStrings, "cat", "dog");
Console.ReadKey();
static void CountTerms(string[] strings, params string[] terms) {
foreach (string term in terms) {
int result = 0;
foreach (string s in strings)
if (s == term)
result++;
Console.WriteLine($"There are {result} instances of {term}");
}
}
With that said, I heavily recommend Ryan Wilson's answer. His version simplifies the task at hand. The only downside to his implementation is if you are implementing this in a singular manner the way List<string>.Count(c => c == "cat") would.
You could try something like:
public int countOccurances(List<string> inputList, string countFor)
{
// Identifiers used are:
int countSoFar = 0;
// Go through your list to count
foreach (string listItem in inputList)
{
// Check your condition
if (listItem == countFor)
{
countSoFar++;
}
}
// Return the results
return countSoFar;
}
this will give you the count for any sting you give it. As always there is a better way but this is a good start.
Or if you want:
public string countOccurances(List<string> inputList, string countFor)
{
// Identifiers used are:
int countSoFar = 0;
string result = countFor;
// Go through your list to count
foreach (string listItem in inputList)
{
// Check your condition
if (listItem == countFor)
{
countSoFar++;
}
}
// Return the results
return countFor + " = " countSoFar;
}
Or an even better option:
private static void CountOccurances(List<string> inputList, string countFor)
{
int result = 0;
foreach (string s in inputList)
{
if (s == countFor)
{
result++;
}
}
Console.WriteLine($"There are {result} occurrances of {countFor}.");
}
Linq is supposed to make developer's life easy. Anyway you could make something like this:
string a = "cat";
string b = "dog";
string c = "cat";
string d = "horse";
var list = new List<string>();
list.Add(a);
list.Add(b);
list.Add(c);
list.Add(d);
var result = GetCount(list);
Console.WriteLine(result);
Console.ReadLine();
static string GetCount(List<string> obj)
{
string result = string.Empty;
int cat = 0;
int dog = 0;
int horse = 0;
foreach (var item in obj)
{
switch (item)
{
case "dog":
dog++;
break;
case "cat":
cat++;
break;
case "horse":
horse++;
break;
}
}
result = "cat = " + cat.ToString() + " dog = " + dog.ToString() + " horse = " + horse.ToString();
return result;
}
I have searched a lot to find a solution to this, but could not find anything. I do however suspect that it is because I don't know what to search for.
First, I have a string that I convert to an array. The string will be formatted like so:
"99.28099822998047,68.375 118.30699729919434,57.625 126.49999713897705,37.875 113.94499683380127,11.048999786376953 96.00499725341797,8.5"
I create the array with the following code:
public static Array StringToArray(string String)
{
var list = new List<string>();
string[] Coords = String.Split(' ', ',');
foreach (string Coord in Coords)
{
list.Add(Coord);
}
var array = list.ToArray();
return array;
}
Now my problem is; I am trying to find a way to convert it back into a string, with the same formatting. So, I could create a string simply using:
public static String ArrayToString(Array array)
{
string String = string.Join(",", array);
return String;
}
and then hopefully replace every 2nd "," with a space (" "). Is this possible? Or are there a whole other way you would do this?
Thank you in advance! I hope my question makes sense.
There is no built-in way of doing what you need. However, it's pretty trivial to achieve what it is you need e.g.
public static string[] StringToArray(string str)
{
return str.Replace(" ", ",").Split(',');
}
public static string ArrayToString(string[] array)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= array.Length-1; i++)
{
sb.AppendFormat(i % 2 != 0 ? "{0} " : "{0},", array[i]);
}
return sb.ToString();
}
If those are pairs of coordinates, you can start by parsing them like pairs, not like separate numbers:
public static IEnumerable<string[]> ParseCoordinates(string input)
{
return input.Split(' ').Select(vector => vector.Split(','));
}
It is easier then to reconstruct the original string:
public static string PrintCoordinates(IEnumerable<string[]> coords)
{
return String.Join(" ", coords.Select(vector => String.Join(",", vector)));
}
But if you absolutely need to have your data in a flat structure like array, it is then possible to convert it to a more structured format:
public static IEnumerable<string[]> Pairwise(string[] coords)
{
coords.Zip(coords.Skip(1), (coord1, coord2) => new[] { coord1, coord2 });
}
You then can use this method in conjunction with PrintCoordinates to reconstruct your initial string.
Here is a route to do it. I don't think other solutions were removing last comma or space. I also include a test.
public static String ArrayToString(Array array)
{
var useComma = true;
var stringBuilder = new StringBuilder();
foreach (var value in array)
{
if (useComma)
{
stringBuilder.AppendFormat("{0}{1}", value, ",");
}
else
{
stringBuilder.AppendFormat("{0}{1}", value, " ");
}
useComma = !useComma;
}
// Remove last space or comma
stringBuilder.Length = stringBuilder.Length - 1;
return stringBuilder.ToString();
}
[TestMethod]
public void ArrayToStringTest()
{
var expectedStringValue =
"99.28099822998047,68.375 118.30699729919434,57.625 126.49999713897705,37.875 113.94499683380127,11.048999786376953 96.00499725341797,8.5";
var array = new[]
{
"99.28099822998047",
"68.375",
"118.30699729919434",
"57.625",
"126.49999713897705",
"37.875",
"113.94499683380127",
"11.048999786376953",
"96.00499725341797",
"8.5",
};
var actualStringValue = ArrayToString(array);
Assert.AreEqual(expectedStringValue, actualStringValue);
}
Another way of doing it:
string inputString = "1.11,11.3 2.22,12.4 2.55,12.8";
List<string[]> splitted = inputString.Split(' ').Select(a => a.Split(',')).ToList();
string joined = string.Join(" ", splitted.Select(a => string.Join(",",a)).ToArray());
"splitted" list will look like this:
1.11 11.3
2.22 12.4
2.55 12.8
"joined" string is the same as "inputString"
Here's another approach to this problem.
public static string ArrayToString(string[] array)
{
Debug.Assert(array.Length % 2 == 0, "Array is not dividable by two.");
// Group all coordinates as pairs of two.
int index = 0;
var coordinates = from item in array
group item by index++ / 2
into pair
select pair;
// Format each coordinate pair with a comma.
var formattedCoordinates = coordinates.Select(i => string.Join(",", i));
// Now concatinate all the pairs with a space.
return string.Join(" ", formattedCoordinates);
}
And a simple demonstration:
public static void A_Simple_Test()
{
string expected = "1,2 3,4";
string[] array = new string[] { "1", "2", "3", "4" };
Debug.Assert(expected == ArrayToString(array));
}
seriously need some guideline on string sorting methodology. Perhaps, if able to provide some sample code would be a great help. This is not a homework. I would need this sorting method for concurrently checking multiple channel names and feed the channel accordingly based on the sort name/string result.
Firstly I would have the string array pattern something like below:
string[] strList1 = new string[] {"TDC1ABF", "TDC1ABI", "TDC1ABO" };
string[] strList2 = new string[] {"TDC2ABF", "TDC2ABI", "TDC2ABO"};
string[] strList3 = new string[] {"TDC3ABF", "TDC3ABO","TDC3ABI"}; //2nd and 3rd element are swapped
I would like to received a string[] result like below:
//result1 = "TDC1ABF , TDC2ABF, TDC3ABF"
//result2 = "TDC1ABI , TDC2ABI, TDC3ABI"
//result3 = "TDC1ABO , TDC2ABO, TDC3ABO"
Ok, here is my idea of doing the sorting.
First, each of the strList sort keyword *ABF.
Then, put all the strings with *ABF into result array.
Finally do Order sort to have the string array align into TDC1ABF, TDC2ABF, TDC3ABF accordingly.
Do the same thing for the other string array inside a loop.
So, my problem is.. how to search *ABF within a string inside a string array?
static void Main()
{
var strList1 = new[] { "TDC1ABF", "TDC1ABI", "TDC1ABO" };
var strList2 = new[] { "TDC2ABF", "TDC2ABI", "TDC2ABO" };
var strList3 = new[] { "TDC3ABF", "TDC3ABO", "TDC3ABI" };
var allItems = strList1.Concat(strList2).Concat(strList3);
var abfItems = allItems.Where(item => item.ToUpper().EndsWith("ABF"))
.OrderBy(item => item);
var abiItems = allItems.Where(item => item.ToUpper().EndsWith("ABI"))
.OrderBy(item => item);
var aboItems = allItems.Where(item => item.ToUpper().EndsWith("ABO"))
.OrderBy(item => item);
}
If you do something like this then you can compare all the sums and arrange them in order. The lower sums are the ones closer to 1st and the higher are the ones that are farther down.
static void Main(string[] args)
{
string[] strList1 = new string[] { "TDC1ABF", "TDC1ABI", "TDC1ABO" };
string[] strList2 = new string[] { "TDC2ABF", "TDC2ABI", "TDC2ABO" };
string[] strList3 = new string[] { "TDC3ABF", "TDC3ABO", "TDC3ABI" };
arrange(strList1);
arrange(strList2);
arrange(strList3);
}
public static void arrange(string[] list)
{
Console.WriteLine("OUT OF ORDER");
foreach (string item in list)
{
Console.WriteLine(item);
}
Console.WriteLine();
for (int x = 0; x < list.Length - 1; x++)
{
char[] temp = list[x].ToCharArray();
char[] temp1 = list[x + 1].ToCharArray();
int sum = 0;
foreach (char letter in temp)
{
sum += (int)letter; //This adds the ASCII value of each char
}
int sum2 = 0;
foreach (char letter in temp1)
{
sum2 += (int)letter; //This adds the ASCII value of each char
}
if (sum > sum2)
{
string swap1 = list[x];
list[x] = list[x + 1];
list[x + 1] = swap1;
}
}
Console.WriteLine("IN ORDER");
foreach (string item in list)
{
Console.WriteLine(item);
}
Console.WriteLine();
Console.ReadLine();
}
If the arrays are guaranteed to have as many elements as there are arrays then you could sort the individual arrays first, dump the sorted arrays into an nxn array and then transpose the matrix.
Building a string for post request in the following way,
var itemsToAdd = sl.SelProds.ToList();
if (sl.SelProds.Count() != 0)
{
foreach (var item in itemsToAdd)
{
paramstr = paramstr + string.Format("productID={0}&", item.prodID.ToString());
}
}
after I get resulting paramstr, I need to delete last character & in it
How to delete last character in a string using C#?
Personally I would go with Rob's suggestion, but if you want to remove one (or more) specific trailing character(s) you can use TrimEnd. E.g.
paramstr = paramstr.TrimEnd('&');
build it with string.Join instead:
var parameters = sl.SelProds.Select(x=>"productID="+x.prodID).ToArray();
paramstr = string.Join("&", parameters);
string.Join takes a seperator ("&") and and array of strings (parameters), and inserts the seperator between each element of the array.
string source;
// source gets initialized
string dest;
if (source.Length > 0)
{
dest = source.Substring(0, source.Length - 1);
}
Try this:
paramstr.Remove((paramstr.Length-1),1);
I would just not add it in the first place:
var sb = new StringBuilder();
bool first = true;
foreach (var foo in items) {
if (first)
first = false;
else
sb.Append('&');
// for example:
var escapedValue = System.Web.HttpUtility.UrlEncode(foo);
sb.Append(key).Append('=').Append(escapedValue);
}
var s = sb.ToString();
string str="This is test string.";
str=str.Remove(str.Length-1);
It's better if you use string.Join.
class Product
{
public int ProductID { get; set; }
}
static void Main(string[] args)
{
List<Product> products = new List<Product>()
{
new Product { ProductID = 1 },
new Product { ProductID = 2 },
new Product { ProductID = 3 }
};
string theURL = string.Join("&", products.Select(p => string.Format("productID={0}", p.ProductID)));
Console.WriteLine(theURL);
}
It's good practice to use a StringBuilder when concatenating a lot of strings and you can then use the Remove method to get rid of the final character.
StringBuilder paramBuilder = new StringBuilder();
foreach (var item in itemsToAdd)
{
paramBuilder.AppendFormat(("productID={0}&", item.prodID.ToString());
}
if (paramBuilder.Length > 1)
paramBuilder.Remove(paramBuilder.Length-1, 1);
string s = paramBuilder.ToString();
paramstr.Remove((paramstr.Length-1),1);
This does work to remove a single character from the end of a string. But if I use it to remove, say, 4 characters, this doesn't work:
paramstr.Remove((paramstr.Length-4),1);
As an alternative, I have used this approach instead:
DateFrom = DateFrom.Substring(0, DateFrom.Length-4);
Add a StringBuilder extension method.
public static StringBuilder RemoveLast(this StringBuilder sb, string value)
{
if(sb.Length < 1) return sb;
sb.Remove(sb.ToString().LastIndexOf(value), value.Length);
return sb;
}
then use:
yourStringBuilder.RemoveLast(",");