is it possible to change the space into underline?

coz i don't know how to program that in C...

please help!!

Dani AI

Generated

Clarification and safe approach (short)

If by "underline" you mean the underscore character _, then yes — replace every space character ' ' with '_'. and were right in intent, and 's example demonstrates the basic idea. Two common pitfalls to avoid: do not modify a string literal (use a writable buffer), and avoid computing a loop limit as strlen(...) - 1 because that can skip the last character or underflow for an empty string.

A simple, robust pattern
Read into a writable buffer (for example with fgets), strip a trailing newline, then iterate from the first character up to the null terminator and replace spaces. Example:

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

int main(void)
{
    char s[256];
    if (!fgets(s, sizeof s, stdin)) return 1;
    s[strcspn(s, "\n")] = '\0';
    for (char *p = s; *p; ++p)
        if (*p == ' ') *p = '_';
    puts(s);
    return 0;
}

Notes, caution, and alternatives

  • If you want to replace any whitespace (tabs, vertical tabs, etc.) use isspace((unsigned char)*p), but remember to cast to unsigned char before calling ctype.h functions.
  • For Unicode (UTF-8) input a single char scan will not catch non-ASCII spaces (no-break space, etc.). Use a Unicode-aware library or wide-character APIs for those cases.
  • For performance on very large buffers, using strchr in a loop to find the next space can be slightly faster than checking every character, but the simple scan above is fine for most uses.

Common mistakes to check for: off-by-one loops, modifying read-only memory, leaving the input newline in place, and passing signed char values to ctype functions.

Recommended Answers

All 3 Replies

If a character is a string, change it to an underscore. Later, rinse, repeat (if necessary).

Post an attempt. Read the announcement in this forum if you need clarification of my last statement.

"If a character is a string, change it to an underscore"
I guess Dave meant
"If a character is a space, change it to an underscore"

Maybe something along these lines should do the job in a simple way.

char* changeString (char* sourceStr)
{
    char* tmpStr = sourceStr;
    int strLength = strlen (tmpStr) - 1;
    for (int i =0; i < strLength; ++i) {
        if ( *(tmpStr + i) == ' ')
            *(tmpStr + i) = '_';
    }
    return tmpStr;
}

int main () {
    char name[BUFSIZ];
    fputs ("\nEnter the string: ");
    fgets (name, BUFSIZ, stdin);
    fputs ("\nThe new string is: ", stdout);
    fputs (changeString(name), stdout);
    getchar ();
    return 0;
}

Hope it helped,
Bye.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.