Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Look at each character in a string

I was wondering if anyone knew how to look through a string at each character and then add each character to a new string? Just a really really basic example, I can add the ToUpper and ToLower validation and such.

like image 246
user1290653 Avatar asked Apr 07 '12 22:04

user1290653


People also ask

How can I see all the characters in a string?

To access character of a string in Java, use the charAt() method. The position is to be added as the parameter. String str = "laptop"; Let's find the character at the 4th position using charAt() method.

How do you find an individual character in a string?

You can use string. indexOf('a') . If the char a is present in string : it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.


2 Answers

string foo = "hello world", bar = string.Empty;  foreach(char c in foo){     bar += c; } 

Using StringBuilder:

string foo = "hello world"; StringBuilder bar = new StringBuilder();  foreach (char c in foo) {     bar.Append(c); } 

Below is the signature of the String class:

[SerializableAttribute] [ComVisibleAttribute(true)] public sealed class String : IComparable,      ICloneable, IConvertible, IComparable<string>, IEnumerable<char>,      IEnumerable, IEquatable<string> 

http://msdn.microsoft.com/en-us/library/system.string(v=vs.100).aspx

like image 74
Alex Avatar answered Oct 04 '22 13:10

Alex


var output = ""; // or use StringBuilder foreach(char c in text) {      output += c; // if or do with c what you need } 

...is that what you needed?
string is IEnumerable<char>

like image 27
NSGaga-mostly-inactive Avatar answered Oct 04 '22 12:10

NSGaga-mostly-inactive