What's a Good Way to Iterate Backwards Through the Characters of a String

What's a good way to iterate backwards through the Characters of a String?

The reversed function reverses a C: CollectionType and returns a ReversedCollection:

for char in "string".characters.reversed() {
// ...
}

If you find that reversed pre-reverses the string, try:

for char in "string".characters.lazy.reversed() {
// ...
}

lazy returns a lazily evaluated sequence (LazyBidirectionalCollection) then reversed() returns another LazyBidirectionalCollection that is visited in reverse.

Best way to loop over a python string backwards

Try the reversed builtin:

for c in reversed(string):
print c

The reversed() call will make an iterator rather than copying the entire string.

PEP 322 details the motivation for reversed() and its advantages over other approaches.

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.

Iterate through a string forwards and backwards, extracting alternating characters

I hope I am understanding your question right. Check the below code.

s = 'shacnidw'
s_odd = ""
s_even = ""
for i in range(len(s)):
if i%2 == 0:
s_even += s[i]
for i in range(len(s), 0, -1):
if i%2 == 1:
s_odd += s[i]

print(s_even + s_odd)

I hope it might help.

Iterate through a string backwards to find a character or phrase

You can use LastIndexOf:

int index = s.LastIndexOf("foo");

It also has an optional start index if you want to start search backwards from somewhere other than the end of the string.

int index = s.LastIndexOf("foo", 20);

How to iterate backwards through a string using for in range ? (application is to validate UPC codes)

What you need here is a little complicated. range by default doesn't go the full way.

for i in range(len(code)-1,-1,-1):

etc. will work but doesn't strike me as very neet. I don't know of another way, perhaps someone else does?

Starting with the last character and iterating backwards by 3

I suggest just iterating the characters in the string, starting from the last position, and moving backwards in increments of 3:

Scanner scnr = new Scanner(System.in);
String str = scnr.nextLine();
String reverse = "";

for (int i=str.length()-1; i >= 0; i=i-3) {
reverse += str.charAt(i);
}

System.out.println(reverse);

Your current approach is failing because the loop just takes single, not triple steps. Also note that you might want to use StringBuilder instead of String to build the reverse string. This might be more efficient (though the JVM itself might substitute StringBuilder on its own).

Iterate backwards through a utf8 multibyte string

A string consists of a series of UTF-8 sequences. All UTF-8 sequences:

  • EITHER consist of exactly one octet (byte to you and me) with the top bit clear

  • OR consist of one octet with the two topmost bits set, followed by one or more octets with bit 7 set and bit 6 clear.

See http://en.wikipedia.org/wiki/Utf8#Description for details.

So what you need to do is to check whether the character concerned has bit 7 set and bit 6 clear, and if so step back one, taking care not to go beyond the start of the string (note that if the string is well formed, this won't happen).

Untested C-ish pseudocode:

char *
findPrevious (const char *ptr, const char *start)
{
do
{
if (ptr <= start)
return NULL; /* we're already at the start of the string */
ptr--;
} while ((*ptr & 0xC0) == 0x80);
return ptr;
}

Loop to print string backwards

You were almost there:

cout << "Your word backwards: ";
for (x = string1.length()-1; x >=0; x--){
cout << string1[x];
}

This way the loop will print each character in string1 but in reverse order, and the text "Your word backwards: " only once.

Reverse the order of characters within words with five letters or more

Hy Pawel Niewolak, the issue is with your reverse function.

Depending on your requirements use that:

 public static String reverse(String s) {
String[] ori = s.split("");
String[] rev = new String[ori.length];

for (int i = 0; i < rev.length; i++) {
rev[i] = ori[rev.length - i - 1];
}
s = "";
for (String str : rev) {
s += str;
}
return s;
}
}


Related Topics



Leave a reply



Submit