For Every Character in String

How do I apply the for-each loop to every character in a String?

The easiest way to for-each every char in a String is to use toCharArray():

for (char ch: "xyz".toCharArray()) {
}

This gives you the conciseness of for-each construct, but unfortunately String (which is immutable) must perform a defensive copy to generate the char[] (which is mutable), so there is some cost penalty.

From the documentation:

[toCharArray() returns] a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.

There are more verbose ways of iterating over characters in an array (regular for loop, CharacterIterator, etc) but if you're willing to pay the cost toCharArray() for-each is the most concise.

For every character in string

  1. Looping through the characters of a std::string, using a range-based for loop (it's from C++11, already supported in recent releases of GCC, clang, and the VC11 beta):

    std::string str = ???;
    for(char& c : str) {
    do_things_with(c);
    }
  2. Looping through the characters of a std::string with iterators:

    std::string str = ???;
    for(std::string::iterator it = str.begin(); it != str.end(); ++it) {
    do_things_with(*it);
    }
  3. Looping through the characters of a std::string with an old-fashioned for-loop:

    std::string str = ???;
    for(std::string::size_type i = 0; i < str.size(); ++i) {
    do_things_with(str[i]);
    }
  4. Looping through the characters of a null-terminated character array:

    char* str = ???;
    for(char* it = str; *it; ++it) {
    do_things_with(*it);
    }

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

I use a for loop to iterate the string and use charAt() to get each character to examine it. Since the String is implemented with an array, the charAt() method is a constant time operation.

String s = "...stuff...";

for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
//Process char
}

That's what I would do. It seems the easiest to me.

As far as correctness goes, I don't believe that exists here. It is all based on your personal style.

How do I iterate over every character in a string and multiply it with the place in its string?

enumerate is convenient for getting an integer index and an element for each iteration.

def f(x):
size = len(x)
for i, char in enumerate(x):
num = i+1 # number of characters
if num == size: # don't print - after last character
ending = ""
else:
ending = "-"
print(num*char, end = ending)

f("string")

Your logic was only a bit off. If we didn't use enumerate and just indexed a string with integers:

def g(x):
size = len(x)
for i in range(size):
num = i+1 # number of characters
if num == size: # don't print - after last character
ending = ""
else:
ending = "-"
print(num*x[i], end = ending)

How to use for-each loop to print each character of string object in Java?

You can get char array from string and iterate in the way doing for char[] in earlier scenario. Below is the code sample:

public class Main {

public static void main(String[] args) {
String abc = "Fida";
//Invoke String class toCharArray() method on string object
for (char a : abc.toCharArray()) {
System.out.println(a);

}

}

}

How to duplicate each character in a string

This will work:


user_input = 'hello'

def double_word(s):
double = ''.join([x+x for x in s])
return double

print(double_word(user_input))


The list comprehension, [x+x for x in s] produces this: ['hh', 'ee', 'll', 'll', 'oo']

''.join() combines the values into a single string.

Iterating each character in a string using Python

As Johannes pointed out,

for c in "string":
#do something with c

You can iterate pretty much anything in python using the for loop construct,

for example, open("file.txt") returns a file object (and opens the file), iterating over it iterates over lines in that file

with open(filename) as f:
for line in f:
# do something with line

If that seems like magic, well it kinda is, but the idea behind it is really simple.

There's a simple iterator protocol that can be applied to any kind of object to make the for loop work on it.

Simply implement an iterator that defines a next() method, and implement an __iter__ method on a class to make it iterable. (the __iter__ of course, should return an iterator object, that is, an object that defines next())

See official documentation

SED - how to add ' ' and , to every character of a string

Corrected version: sed -r 's/(.{1})/'\''\1'\'',/g;s/,$//' - the backreference should be between the quotes. Not sure whether you need the space after comma or not, I deleted it to allow the second s command to match.

You can also use \x27 to represent single quote character:

$ echo 'STRING#!-@' | sed 's/./\x27&\x27,/g; s/,$//'
'S','T','R','I','N','G','#','!','-','@'

& will have entire text matched by the regexp, so no need to use capture groups for this case.

Other notes:

  • No need to use cat file | sed '..', you can use sed '..' file
  • -E is more portable these days compared to -r
  • .{1} is same as .

How can I process each letter of text using Javascript?

If the order of alerts matters, use this:

for (var i = 0; i < str.length; i++) {
alert(str.charAt(i));
}

Or this: (see also this answer)

 for (var i = 0; i < str.length; i++) {
alert(str[i]);
}

If the order of alerts doesn't matter, use this:

var i = str.length;
while (i--) {
alert(str.charAt(i));
}

Or this: (see also this answer)

 var i = str.length;
while (i--) {
alert(str[i]);
}