DEV Community

Cover image for How to Iterate over String
Azad Kshitij
Azad Kshitij

Posted on

2 2

How to Iterate over String

If you are just getting started with competitive programming you will definitely come across problem where you have to iterate over a string.

Questions to try

  1. https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/
  2. https://leetcode.com/problems/defanging-an-ip-address/
  3. https://leetcode.com/problems/split-a-string-in-balanced-strings/

I have the answer in different programming languages.

C++

#include <iostream>
#include <string>

int main ()
{
  std::string str ("dev.to");
  for (unsigned i=0; i<str.length(); ++i)
  {
    std::cout << str.at(i);
  }
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

output: dev.to

Python

Iterating over string is as simple as iterating over a list in python.

string  = "dev.to"
for i in string:
    print(i)
Enter fullscreen mode Exit fullscreen mode
output: 
d
e
v
.
t
o
Enter fullscreen mode Exit fullscreen mode

C

#include <stdio.h>
#include <string.h>

int main(void){
    char source[] = "dev.to";
    for (int i = 0; i < strlen(source); i++) {
        printf("%c",source[i]);
    }
}
Enter fullscreen mode Exit fullscreen mode

output: dev.to

IMPORTANT: This are not the only ways to get your job done but are easy to understand for beginner.

You can search google for answer or just save this post. More to come in future with this series.

Suggest me if you have anything to say because this is my first post on dev.to.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay