DEV Community

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

Posted on

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.

Top comments (0)