I have a string where I need to do substring operation. I'm trying to achieve something like this for example if the input string is com then the output must be something like this -
c
co
com
o
om
m.. I have tried this
for(int i=0 ; i<len ;i++)
{
printf("%s",&string[strlen(string)-i]));
}
A substring is defined by its left and right ends so there are O(n*n) substrings in a string of length n.
int n = strlen(string);
for(int i = 0; i < n; i++)
{ for(int j = i; j < n; j++)
{ /* print substring from i to j */
for(int k = i; k <= j; k++)
{ printf("%c", string[k]);
}
printf("\n");
}
}
You're missing a comma in your code:
for(int i=0 ; i<len ;i++)
{
printf("%s", &string[strlen(string)-i])
}
But that will print "", "m", "om" - not what you want.
Something more like:
// start at each point in the string
for ( const char *start = string; *start; ++start )
{
// for each starting point, go from the whole remainder down
// to just one character
for ( const char *end = string + strlen(string); end > start; --end )
{
for ( const char *s = start; s < end; ++s )
putchar(*s);
putchar('\n');
}
}
Example: https://ideone.com/XXoYv6
Substring means any contiguous group of characters.
For the n string
it will generate (n*(n-1) /2) substrings.
For example of String
source = "STACK"
Length of the character is 5, so it total substring would be (5(5-1) /2) = 10
We have to iterate through the first element of string and print all the substring and than onwards one by one we increment the index of i and printing the substring from range (j to k)
public void generateSubString(String source){
char[] arr = source.toCharArray();
for(int i = 0; i<arr.length; i++){
for(int j = i ; j < arr.length; j++){
for(int k = i; k<=j; k++){
System.out.print(arr[k]);
}
System.out.println();
}
OUTPUT:
S
ST
STA
STAC
STACK
T
TA
TAC
TACK
A
AC
ACK
C
CK
K
Below is the code to find all substrings of a string in javascript without for loop, which will increase the speed of code.
const devideSubStr = (str) => {
var totalLoop = str.length * ((str.length + 1)/2);
// looping count
let i = 0;
var totalChar = 1;//character to get
var charFrom = 0;// from which index
var strLength = str.length;//length of digit
while( i < totalLoop){
console.log(str.substr(charFrom, totalChar))
charFrom ++;
i ++;
if(charFrom == strLength){
charFrom = 0;
strLength = strLength - 1;
totalChar ++;
}
}}
Related
I am trying to create a function to identify whether or not a character is repeated in a given string.
int checkrow(char* row) {
int count, r;
for(int i = 0; i < strlen(row); i++) {
count = 1;
for(int j = i + 1; j < strlen(row); j++) {
if(row[i] == row[j]) {
count = count + 1;
}
}
if(count > 1 ) {
r = 0;
}
else {
r = 1;
}
}
return r;
}
This is my function at the moment, I am not getting an error or warning messages, but it is not identifying repeated characters.
I am very new to C and any help would be appreciated!
For each character you test, you set r to whether that character is repeated. So if the first character is repeated you set r = 0, but then if the second character is not repeated, you set r = 1.
You don't need to test every character. As soon you find a repeated character, you can return 0. If you get to the end of the loop, nothing was repeated, so you return 1.
int checkrow(char* row) {
for(size_t i = 0; i < strlen(row); i++) {
for(size_t j = i + 1; j < strlen(row); j++) {
if(row[i] == row[j]) {
return 0;
}
}
}
return 1;
}
I'm actually implementing a shuffling function with an un-shuffling function. I'm using the Fisher-Yates algorithm with pseudo random number generator with a fixed seed. The unshuffled string doesn't look like the initial string, however.
I've checked if my random array is the same in the shuffling function and the un-shuffling function. The unshuffling function is the same as the shuffling function but in reverse.
Here is my shuffling function :
void shuffle(char * phrase)
{
int size_phrase = strlen(phrase);
srand(seed);
int * rdm_array = (int*)malloc(sizeof(int)*size_phrase);
int i;
for(i = 0; i < size_phrase; i++)
{
rdm_array[i] = rand()%size_phrase;
//printf("%d", rdm_array[i]);
}
//begin shuffle here
int j;
int k = 0;
for(j = size_phrase -1 ; j > 0 ; j-- , k++)
{
int rdm_nb = rdm_array[k];
char temp = phrase[j];
phrase[j] = phrase[rdm_nb];
phrase[rdm_nb] = temp;
}
free(rdm_array);
}
And here is my unshuffling function :
void unshuffle(char * phrase)
{
int size_phrase = strlen(phrase);
srand(seed);
int * rdm_array = (int*)malloc(sizeof(int)*size_phrase);
int i;
for(i = 0; i < size_phrase; i++)
{
rdm_array[i] = rand()%size_phrase;
//printf("%i", rdm_array[i]);
}
//On commence le mélange ici
int j;
int k = size_phrase-1;
for(j = 0 ; j < size_phrase ; j++ , k--)
{
int rdm_nb = rdm_array[k];
char temp = phrase[j];
phrase[j] = phrase[rdm_nb];
phrase[rdm_nb] = temp;
}
free(rdm_array);
}
And here is my Output :
It looks like it's missing one loop or something like that.
Add a printf to show what gets exchanged in both shuffle and unshuffle like this
/* after this line */
int rdm_nb = rdm_array[k];
/* insert debug output */
printf("%d <-> %d\n", j, rdm_nb);
You will see that in function shuffle variable j counts from size_phrase -1 to 1 while in unshuffle it counts from 0 to size_phrase -1.
Probably you should change the for loop in shuffle to
for(j = size_phrase -1 ; j >= 0 ; j-- , k++)
I have to make a program that sort strings (with exact length 7 chars) by using radix sort. I already made a function that sort each column separately. My problem is how to make the whole string move, not just one char. It's really problematic for me to see how should it work in C.
I made one array "char strings[3][8]" and "char output[3][8]" to get sorted 3 strings with exact 7 chars in each one. For example sorting these strings:
strcpy(strings[0], "kupbars");
strcpy(strings[1], "daparba");
strcpy(strings[2], "jykaxaw");
In output I get:
dakaaaa
juparbs
kypbxrw
Each column is sorted correctly but chars don't stick together. I tried many ways for 3 hours but nothing works.
My code looks like this:
void countingSort(char a[][8], char b[][8]) {
int c[123];
for (int pos = 6; pos >= 0; pos--) {
for (int i = 0; i < 123; i++)
c[i] = 0;
for (int i = 0; i < 3; i++)
c[(int)a[i][pos]]++;
for (int i = 1; i < 123; i++)
c[i] += c[i - 1];
for (int i = 2; i >= 0; i--) {
b[--c[(int)a[i][pos]]][pos] = a[i][pos];
}
}
}
(There are constants limiting string length etc. because it's easy to change it to variable - I just focused on getting this program work properly.)
Try changing the loop to move an entire string:
for (int i = 2; i >= 0; i--) {
int k = --c[(int)a[i][pos]];
for(int j = 0; j < 8; j++) {
b[k][j] = a[i][j];
}
}
You could do a circular list but it's a little overhead. I propose you to use memmove().
#include <string.h>
void array_move_forward(char array[3][8]) {
for (int i = 0; i < 3; i++) {
char tmp = array[i][6];
memmove(array[i] + 1, array[i], 6);
array[i][0] = tmp;
}
}
void array_move_rewind(char array[3][8]) {
for (int i = 0; i < 3; i++) {
char tmp = array[i][0];
memmove(array[i], array[i] + 1, 6);
array[i][6] = tmp;
}
}
A other solution would be to manipulate your string yourself and using a index, that indicate the first letter of your string.
{
char str[7];
int i = 0;
...
int j = i;
for (int k = 0; k < 7; k++) {
char tmp = str[j++ % 7];
}
}
With that you could rotate your string just with i++ or i--.
struct my_string_radix {
char str[7];
int begin;
}
I'am trying to write a program for converting the given string in cross manner(i.e Diagonal from left-right and from right-left). If the string length is even it returns a message else arrange it in a cross form.
The code is:
#include<stdio.h>
#include<string.h>
int main()
{
char str[50];
char str2[50][50];
int lenstr;
int i,j;
char temp;
printf("Enter the string :\n");
scanf("%s",str);
lenstr = strlen(str);
if(lenstr %2 == 0)
{
printf("The string length must be an odd length");
}
else
{
j = 0;
temp = 0;
for(i = 0;i == lenstr;i++)
{
str2[i][j] = str[i];
j = j + 1;
}
for(i = lenstr; i==0 ;i--)
{
j = lenstr;
str2[i][j] = str[temp];
temp = temp + 1;
j = j - 1;
}
for(i = 0;i<lenstr;i++)
{
for(j = 0;j<lenstr;j++)
{
printf("%c",str2[i][j]);
}
printf("\n");
}
}
return 0;
}
The output to the program must be for example: geeks
g g
e e
e
k k
s s
But the output obtained consists of different shapes(like heart,smiley face etc...). Explain the concept behind to correct it and if can please explain when using pointers for the same program. Any help appreciated.
In your code, you need to change the for loop condition checking expressions, like i == lenstr and later i==0. They are not entering the loop, essentially.
Instead, you can replace the whole block
for(i = 0;i == lenstr;i++)
{
str2[i][j] = str[i];
j = j + 1;
}
for(i = lenstr; i==0 ;i--)
{
j = lenstr;
str2[i][j] = str[temp];
temp = temp + 1;
j = j - 1;
}
in your code by
for(i = 0;i<lenstr;i++)
for(j = 0;j<lenstr;j++)
str2[i][j] = ' '; //fill 2D array with space
for(i = 0;i < lenstr;i++)
{
str2[i][i] = str[i]; //set the character
str2[i][lenstr- i -1] = str[i]; //reverse position
}
and get the desired output.
See it LIVE.
Your logic to store diagonal string seems to be wrong. In the first loop you store left-right diagonal and your index goes from 0 to length-1 and your column starts from 0; increment it by 1. Its same for right-left diagonal, only difference being column starts from length-1 and ends at 0. Hence you need to initialize temp = lenstr -1;
temp = lenstr -1;
for(i = 0;i <lenstr;i++)
{
str2[i][j] = str[i];
j = j + 1;
}
for(i = 0;i <lenstr;i++)
{
str2[i][temp] = str[i];
temp = temp - 1;
}
I think the problem is that str2 is not getting initialized. The first two for loops should be something like
for(i = 0;i < lenstr;i++)
and
for(i = lenstr; i>=0 ;i--)
Here is my five cents. The program allows to enter words with an odd or even number of letters.
Enjoy!:)
#include <stdio.h>
#include <string.h>
#define N 25
int main(void)
{
while ( 1 )
{
char s[N];
printf( "Enter a string less than %zu characters (Enter-exit): ", N );
if ( !fgets( s, N, stdin ) || s[0] == '\n' ) break;
size_t n = strlen( s );
if ( s[n-1] == '\n' ) s[--n] = '\0';
printf( "\n" );
for ( size_t i = 1, j = n; i <= n; i++, j-- )
{
char c = s[i-1];
if ( i < j ) printf( "%*c%*c\n", i, c, j - i, c );
else if ( j < i ) printf( "%*c%*c\n", j, c, i - j, c );
else printf( "%*c\n", i, c );
}
}
return 0;
}
If to enter
Stackoverflow
hello
then the program output will be
Enter a string less than 25 characters (Enter-exit): Stackoverflow
S S
t t
a a
c c
k k
o o
v
e e
r r
f f
l l
o o
w w
Enter a string less than 25 characters (Enter-exit): hello
h h
e e
l
l l
o o
Enter a string less than 25 characters (Enter-exit):
import java.util.*;
public class CrossCharacter {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String str = in.next();
int len = str.length();
char[][] ch_matrix = new char[len][len];
len--;
for(int i=0;i<=len;i++)
ch_matrix[i][i] = ch_matrix[i][len-i] = str.charAt(i);
for(int i=0;i<=len;i++){
for(int j=0;j<=len;j++)
System.out.print(ch_matrix[i][j]);
System.out.println();
}
}
}
# include<stdio.h>
void main() {
char n[100],temp;
int i = 0, j;
scanf("%s", &n);
m = strlen(n);
for(i = 0; i <= m - 1;)
temp[i];
i++;
for(j = 0; j < m - 1; j++)
{
if(i == j + 1 || j == m - 1 - i + 1)
printf("%c",temp);
else
printf(" "):
}
printf("\n");
getch();
}
Need to figure out a code that counts all the repeating symbols in a string. As you can see below, so far so good.
And here starts the tricky part, at the end of the code I want to output symbols in an order they were typed which had for example 2 occurences in a string, and I got problems figuring that out.
int counts[256] = { 0 };
int i;
size = strlen(text);
for (i = 0; i < size; i++) {
counts[(int)(text[i])]++;
}
for (i = 0; i < 256; i++) {
printf("The %d. character has %d occurrences.\n", i, counts[i]);
}
Just iterate through the source string again and for each character look into your counts array.
If you don't want to print the same statistics for every occurence of repeating character, you can reset the corresponding counts value to zero just after you print the statistics, and have an additional check before printing.
for(i = 0; i < size; i++) {
if(counts[(int)(text[i])] == 2)
printf("%d", (int)(text[i]));
The first line loops through your source string for the order of occurences.
The second line checks if it was captured in the counts array as occuring only twice.
If it was we print the char code on the third line.
To only print the character once:
for(i = 0; i < size; i++) {
if(counts[(int)(text[i])] == 2) {
printf("%d", (int)(text[i]));
counts[(int)(text[i])] = 0;
}
}
Here is an implementation of Inspired's answer:
int counts[256] = { 0 };
char text[] = "Hello, world!";
int i, size = strlen(text);
for (i = 0; i < size; i++)
{
counts[(unsigned int)(text[i])]++;
}
for (i = 0; i < size; i++)
{
if (counts[(unsigned int)text[i]] > 1)
{
printf("%c", text[i]);
counts[(unsigned int)text[i]] = 0; // Remove to print repeats.
}
}
Make a key,count pair, like:
#include <string.h>
#include <stdio.h>
int main()
{
char* text = "count this text";
char *keys = new char[strlen(text)];
int* count = new int[strlen(text)];
int last = 0; int j=0;
for(int i=0; i<strlen(text); i++){
for(j=0; j<last; j++){
if(keys[j]==text[i]) break;
}
if(keys[j]==text[i]){
count[j]++;
} else {
keys[last]=text[i];
count[last]=1;
last++;
}
}
for(int i=0; i<last; i++){
printf("%c %d\n", keys[i], count[i]);
}
}
so you keep the order in the text and get the count.
On execution the output is:
c 1
o 1
u 1
n 1
t 4
2
h 1
i 1
s 1
e 1
x 1