How to Convert an ArrayList to string C# - string

ArrayList arr = new ArrayList();
string abc =
What should I do to convert arraylist to a string such as abc = arr;Updated QuestOther consideration from which i can complete my work is concatination of string(need help in that manner ). suppose i have a string s="abcdefghi.."by applying foreach loop on it and getting char by matching some condition and concatinating every char value in some insatnce variable of string type i.e string subString=+;Something like thisstring tem = string.Empty;
string temp =string.Empty;
temp = string.Concat(tem,temp);

Using a little linq and making the assumption that your ArrayList contains string types:
using System.Linq;
var strings = new ArrayList().Cast<string>().ToArray();
var theString = string.Join(" ", strings);
Further reading:
http://msdn.microsoft.com/en-us/library/57a79xd0.aspx
For converting other types to string:
var strings = from object o in myArrayList
select o.ToString();
var theString = string.Join(" ", strings.ToArray());
The first argument to the Join method is the separator, I chose whitespace. It sounds like your chars should all contribute without a separator, so use "" or string.Empty instead.
Update: if you want to concatenate a small number of strings, the += operator will suffice:
var myString = "a";
myString += "b"; // Will equal "ab";
However, if you are planning on concatenating an indeterminate number of strings in a tight loop, use the StringBuilder:
using System.Text;
var sb = new StringBuilder();
for (int i = 0; i < 10; i++)
{
sb.Append("a");
}
var myString = sb.ToString();
This avoids the cost of lots of string creations due to the immutability of strings.

Look into string.Join(), the opposite of string.Split()
You'll also need to convert your arr to string[], I guess that ToArray() will help you do that.

Personally and for memory preservation I’ll do for a concatenation:
System.Collections.ArrayList Collect = new System.Collections.ArrayList();
string temporary = string.Empty;
Collect.Add("Entry1");
Collect.Add("Entry2");
Collect.Add("Entry3");
foreach (String var in Collect)
{
temporary = temporary + var.ToString();
}
textBox1.Text = temporary;

Related

How to concatenate two string in Dart?

I am new to Dart programming language and anyone help me find the best string concatenation methods available in Dart.
I only found the plus (+) operator to concatenate strings like other programming languages.
There are 3 ways to concatenate strings
String a = 'a';
String b = 'b';
var c1 = a + b; // + operator
var c2 = '$a$b'; // string interpolation
var c3 = 'a' 'b'; // string literals separated only by whitespace are concatenated automatically
var c4 = 'abcdefgh abcdefgh abcdefgh abcdefgh'
'abcdefgh abcdefgh abcdefgh abcdefgh';
Usually string interpolation is preferred over the + operator.
There is also StringBuffer for more complex and performant string building.
If you need looping for concatenation, I have this :
var list = ['satu','dua','tiga'];
var kontan = StringBuffer();
list.forEach((item){
kontan.writeln(item);
});
konten = kontan.toString();
Suppose you have a Person class like.
class Person {
String name;
int age;
Person({String name, int age}) {
this.name = name;
this.age = age;
}
}
And you want to print the description of person.
var person = Person(name: 'Yogendra', age: 29);
Here you can concatenate string like this
var personInfoString = '${person.name} is ${person.age} years old.';
print(personInfoString);
Easiest way
String get fullname {
var list = [firstName, lastName];
list.removeWhere((v) => v == null);
return list.join(" ");
}
The answer by Günter covers the majority of the cases of how you would concatenate two strings in Dart.
If you have an Iterable of Strings it will be easier to use writeAll as this gives you the option to specify an optional separator
final list = <String>['first','second','third'];
final sb = StringBuffer();
sb.writeAll(list, ', ');
print(sb.toString());
This will return
'first, second, third'
Let's think we have two strings
String a = 'Hello';
String b = 'World';
String output;
Now we want to concat this two strings
output = a + b;
print(output);
Hello World

How to collect a string to a stack of characters in Java 8? [duplicate]

I would like to convert the string containing abc to a list of characters and a hashset of characters. How can I do that in Java ?
List<Character> charList = new ArrayList<Character>("abc".toCharArray());
In Java8 you can use streams I suppose.
List of Character objects:
List<Character> chars = str.chars()
.mapToObj(e->(char)e).collect(Collectors.toList());
And set could be obtained in a similar way:
Set<Character> charsSet = str.chars()
.mapToObj(e->(char)e).collect(Collectors.toSet());
You will have to either use a loop, or create a collection wrapper like Arrays.asList which works on primitive char arrays (or directly on strings).
List<Character> list = new ArrayList<Character>();
Set<Character> unique = new HashSet<Character>();
for(char c : "abc".toCharArray()) {
list.add(c);
unique.add(c);
}
Here is an Arrays.asList like wrapper for strings:
public List<Character> asList(final String string) {
return new AbstractList<Character>() {
public int size() { return string.length(); }
public Character get(int index) { return string.charAt(index); }
};
}
This one is an immutable list, though. If you want a mutable list, use this with a char[]:
public List<Character> asList(final char[] string) {
return new AbstractList<Character>() {
public int size() { return string.length; }
public Character get(int index) { return string[index]; }
public Character set(int index, Character newVal) {
char old = string[index];
string[index] = newVal;
return old;
}
};
}
Analogous to this you can implement this for the other primitive types.
Note that using this normally is not recommended, since for every access you
would do a boxing and unboxing operation.
The Guava library contains similar List wrapper methods for several primitive array classes, like Chars.asList, and a wrapper for String in Lists.charactersOf(String).
The lack of a good way to convert between a primitive array and a collection of its corresponding wrapper type is solved by some third party libraries. Guava, a very common one, has a convenience method to do the conversion:
List<Character> characterList = Chars.asList("abc".toCharArray());
Set<Character> characterSet = new HashSet<Character>(characterList);
Use a Java 8 Stream.
myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());
Breakdown:
myString
.chars() // Convert to an IntStream
.mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
.collect(Collectors.toList()); // Collect in a List<Character>
(I have absolutely no idea why String#chars() returns an IntStream.)
The most straightforward way is to use a for loop to add elements to a new List:
String abc = "abc";
List<Character> charList = new ArrayList<Character>();
for (char c : abc.toCharArray()) {
charList.add(c);
}
Similarly, for a Set:
String abc = "abc";
Set<Character> charSet = new HashSet<Character>();
for (char c : abc.toCharArray()) {
charSet.add(c);
}
List<String> result = Arrays.asList("abc".split(""));
Create an empty list of Character and then make a loop to get every character from the array and put them in the list one by one.
List<Character> characterList = new ArrayList<Character>();
char arrayChar[] = abc.toCharArray();
for (char aChar : arrayChar)
{
characterList.add(aChar); // autoboxing
}
You can do this without boxing if you use Eclipse Collections:
CharAdapter abc = Strings.asChars("abc");
CharList list = abc.toList();
CharSet set = abc.toSet();
CharBag bag = abc.toBag();
Because CharAdapter is an ImmutableCharList, calling collect on it will return an ImmutableList.
ImmutableList<Character> immutableList = abc.collect(Character::valueOf);
If you want to return a boxed List, Set or Bag of Character, the following will work:
LazyIterable<Character> lazyIterable = abc.asLazy().collect(Character::valueOf);
List<Character> list = lazyIterable.toList();
Set<Character> set = lazyIterable.toSet();
Bag<Character> set = lazyIterable.toBag();
Note: I am a committer for Eclipse Collections.
IntStream can be used to access each character and add them to the list.
String str = "abc";
List<Character> charList = new ArrayList<>();
IntStream.range(0,str.length()).forEach(i -> charList.add(str.charAt(i)));
Using Java 8 - Stream Funtion:
Converting A String into Character List:
ArrayList<Character> characterList = givenStringVariable
.chars()
.mapToObj(c-> (char)c)
.collect(collectors.toList());
Converting A Character List into String:
String givenStringVariable = characterList
.stream()
.map(String::valueOf)
.collect(Collectors.joining())
To get a list of Characters / Strings -
List<String> stringsOfCharacters = string.chars().
mapToObj(i -> (char)i).
map(c -> c.toString()).
collect(Collectors.toList());

Add comma sequentially to string in C#

I have a string.
string str = "TTFTTFFTTTTF";
How can I break this string and add character ","?
result should be- TTF,TTF,FTT,TTF
You could use String.Join after you've grouped by 3-chars:
var groups = str.Select((c, ix) => new { Char = c, Index = ix })
.GroupBy(x => x.Index / 3)
.Select(g => String.Concat(g.Select(x => x.Char)));
string result = string.Join(",", groups);
Since you're new to programming. That's a LINQ query so you need to add using System.Linq to the top of your code file.
The Select extension method creates an anonymous type containing the char and the index of each char.
GroupBy groups them by the result of index / 3 which is an integer division that truncates decimal places. That's why you create groups of three.
String.Concat creates a string from the 3 characters.
String.Join concatenates them and inserts a comma delimiter between each.
Here is a really simple solution using StringBuilder
var stringBuilder = new StringBuilder();
for (int i = 0; i < str.Length; i += 3)
{
stringBuilder.AppendFormat("{0},", str.Substring(i, 3));
}
stringBuilder.Length -= 1;
str = stringBuilder.ToString();
I'm not sure if the following is better.
stringBuilder.Append(str.Substring(i, 3)).Append(',');
I would suggest to avoid LINQ in this case as it will perform a lot more operations and this is a fairly simple task.
You can use insert
Insert places one string into another. This forms a new string in your C# program. We use the string Insert method to place one string in the middle of another one—or at any other position.
Tip 1:
We can insert one string at any index into another. IndexOf can return a suitable index.
Tip 2:
Insert can be used to concatenate strings. But this is less efficient—concat, as with + is faster.
for(int i=3;i<=str.Length - 1;i+=4)
{
str=str.Insert(i,",");
}

Remove some text from a string after some constant value(string)

Input: String str="Fund testing testing";
Output: str="Fund";
After fund whatever the text is there need to remove that text.
Please suggest some solution.
The easiest way to solve this is a .Substring() method, as you can provide it the start index of your original string and length of the string you need:
var length = "Fund".Length;
var str = "Fund testing testing";
Console.WriteLine(str.Substring(0, length)); //returns "Fund"
var str1 = "testFund testing testing";
Console.WriteLine(str1.Substring(4, length)); //returns "Fund"
var str2 = "testFund testing testing";
Console.WriteLine(str2.Substring(str2.IndexOf("Fund"), length)); //returns "Fund"
You can also use regular expression like this:
string strRegex = #".*?(Fund).*";
Regex myRegex = new Regex(strRegex, RegexOptions.Singleline);
string strTargetString = #"Fund testing testing";
string strReplace = #"$1";
return myRegex.Replace(strTargetString, strReplace);
As mentioned in comments below, replace can lack performance and is kind of overkill, so regex Match can be better. Here is how it looks like:
string strRegex = #".*?(Fund).*";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = "\n\n" + #" Fund testing testing";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
var fund = myMatch.Groups[1].Value;
Console.WriteLine(fund);
}
}
Note that Groups first element is your entire match

How to cut a set of characters in a stringbuilder?

Is there a way to split a set of characters in a stringbuilder - for example if I have "One Two Three Four" is there a way of getting each individual word which I could then put into a list (using a foreach loop)
I think there is no direct way to split StringBuilder to an array, you need convert to String first, like this:
StringBuilder sb = new StringBuilder();
sb.append("One Two Three Four");
String[] myArray = sb.toString().split(" ");
for java
StringBuilder sb = new StringBuilder("One Two Three Four");
String[] words = sb.toString().split("[\\s]+");
please try using the below mentioned code. Hope it helps you in your task :
//Create Stringbuilder
StringBuilder strb = new StringBuilder();
strb.Append("One Two Three Four");
// Convert Stringbuilder to string
string a = strb.ToString();
// Split the string based on seprator. Here seprator is space " "
string[] str = a.Split();
List<string> al1 = new List<string>();
// Add the word of splited string to a string List
foreach (string str1 in str)
{
al1.Add(str1);
}

Resources