How to cut a set of characters in a stringbuilder? - string

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);
}

Related

Creating string from Custom label

I have a custom label in CSV format called Test having value abc, xyz and I want to create a string in the form 'abc','xyz'. How would we do that?
Code Written so far
String str = System.Label.Test;
// next steps
The code below splits the label at the comma to create a list. Each string in the list is them trimmed to remove whitespace and added to another list. That list is joined using ',' as the delimiter.
String str = System.Label.Test; // next steps
final String SINGLE_QUOTE = '\'';
final String COMMA = ',';
final String DELIMITER = SINGLE_QUOTE + COMMA + SINGLE_QUOTE;
String formattedLabel = SINGLE_QUOTE;
List<String> stringItems = new List<String>();
for(String item : str.split(',')){
stringItems.add(item.trim());
}
formattedLabel += String.join(stringItems, DELIMITER);
formmatedLabel += SINGLE_QUOTE;
System.debug(formattedLabel);

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());

When trying to add a space back into a tokenized String, why are two spaces added into my output?

Beginner here. Sorry for the vague title but the code should put my question into perspective.
public static void main(String [] args)
{
String sentence = "hi. how are you! i'm just dandy.";
String tokenSent;
tokenSent = sentenceCapitalizer(sentence);
System.out.println(tokenSent);
}
public static String sentenceCapitalizer(String theSentence)
{
StringTokenizer strTokenizer = new StringTokenizer(theSentence, ".!", true);
String token = null;
String totalToken = "";
String ch = "";
while(strTokenizer.hasMoreTokens())
{
token = strTokenizer.nextToken().trim();
token = token.replace(token.charAt(0), Character.toUpperCase(token.charAt(0)));
StringBuilder str = new StringBuilder(token);
str.append(" ");
totalToken += str;
}
return totalToken;
}
OUTPUT AS IS: Hi . How are you ! I'm just dandy .
I was able to capitalize the first letter of each sentence but I'm wanting the output to keep the same format as the original String. The problem is that it puts a space before and after the ending punctuation. Is there any way to fix this problem using only a StringBuilder and/or StringTokenizer? Thank you for your time.
You can do this.
String delim = ".!";
StringTokenizer strTokenizer = new StringTokenizer(theSentence, delim, true);
Then,
if(delim.contains(token))
str.append(" ");
When you declare new StringTokenizer(theSentence, ".!", true) ,true enables to return delimiter characters also as next token. Since you appending a space to each token, it is normal to get that output.
You can check if the token is a delimiter character, if so, you add the space.
if(token.length() == 1 &&
delims.indexOf(token.charAt(0)) != -1)
str.append(" "); //we just hit the delim char, add space

How to Convert an ArrayList to string C#

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;

Resources