How to concatenate strings in Sway?

Given two strings:

let a: str = "a";
let b: str = "b";

How can I concatenate them to produce the string “ab”?

1 Like

Hey @mpoplavkov, to concatenate strings, the current method to use is:

pub fn concat(a: String, b: String) -> String {
    let mut a = a.as_bytes();
    let b = b.as_bytes();
    a.append(b);
    String::from_ascii(a)
}

This functionality didn’t make it to the standard library because the implementation was considered too rough. The Sway team is currently reworking Strings entirely in Sway, so you can use this method in the meantime.

1 Like

I’m getting errors with the reason MemoryOwnership for some of the inputs (not all of them) when I’m using this function :thinking:

Not sure what the exact reason of this could be. Maybe the fact that the bytes in b are cleared after the call to append. I rewrote the function in the following way and now it works for me:

fn push_bytes(ref mut a: Bytes, b: Bytes) {
    let mut i = 0;
    while i < b.len() {
        a.push(b.get(i).unwrap());
        i = i + 1;
    }
}

fn concat(a: String, b: String) -> String {
    let mut result = Bytes::new();
    push_bytes(result, a.as_bytes());
    push_bytes(result, b.as_bytes());
    String::from_ascii(result)
}
1 Like

Appreciate you for bringing this up @mpoplavkov :slight_smile: going to share this with the Sway team!

1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.