1

I'm trying to write a C program that only prints the last occurrence of repeating letters of a string. I have that part done but I want to store all those chars in a string. What I have so far is:

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

bool isLast(char *arg1, char ch, int p) {
  p++;
  while (arg1[p] != '\0') {
    if ((arg1[p]) == ch) {
      return false;
    }
    p++;
  }
  return true;
}

int main() {
  char *word = "kaax";
  char *vals = "1235";
  char *result = "";

  for (int i = 0; word[i] != '\0'; i++) {
    if (isLast(word, word[i], i)) {
      result += vals[i];
    }
  }
  printf("%s", result);
}

I want:

printf("%s",result);

to print:

fxkav

Since that is the logical result of my program and what the output should be.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • format your code. – 0___________ Dec 12 '20 at 13:19
  • It looks like you've learned to code in a different language. C strings are quite primitive and can't do the things you can do in nearly every other language. I think it's necessary to do some reading of a good introductory C book since it's very difficult to learn C from just doing since there are many traps and wrong ways of doing things that are not obvious (and may not even fail all the time). https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list has a good list – Paul Hankin Dec 12 '20 at 13:24

1 Answers1

1

How to phrase it ... Not at all.

Your "empty string" is a string literal of size 1 (containing only '\0'. It cannot be changed and even lesss extended.

If you need to manipulate "strings" (which in C is not really an existing concept) you need to represent them as sequences of characters, which are stored in a data structure which allows to change the contained characters and, in your case, also has space for more characters.

In cases where you can determine a maximum size (MAXSIZE) you could define an array of characters of that size like this

char SizedCharArray[MAXSIZE];
Yunnosch
  • 26,130
  • 9
  • 42
  • 54